所以我已经为此工作了几个小时,但我似乎无法弄清楚如何对角搜索2D charr数组。为此,我已经弄清楚了如何进行垂直和水平搜索。另外,我希望能对角找到所有4个方向的单词(左上方->右下方/右下方->左上方/右上方->左下方/右上方->左下方) 这就是我到目前为止所得到的
public void searchDiagonal() {
char [][] grid = //is a [15][15] array
char[] sample = {'W','O','R','D'}
int startR = 0;
int startC = 0;
int endR = 0;
int endC = 0;
boolean wordFound = false;
int row = 0;
for(int i = grid.length - 1; i >= 0; i--)
{
if(i == grid.length - 1) {
//check the middle diagonal
for(int j = grid.length - 1; j >= 0; j--) {
int index = 0;
if(sample[index] == grid[j][j])
{
startR = j;
startC = j;
if(index == sample.length - 1) {
//word has been found
endR = j;
endC = j;
wordFound = true;
System.out.println("Word found at [" + startR + "][" + startC + "] & ["
+ endR + "][" + endC + "]");
break;
}
index++;
}
if(wordFound)
break;
}
}
}
for(int i = grid.length - 1; i >= 0; i--) {
for(int j = grid.length - 1; j >= 0; j--) {
}
//now i will handle up/down and row will handle left/right [row][i]
if(i == 13) {
row = 14;
}
int index = 0;
if(sample[index] == grid[row][i])
{
if(index == 0) {
startR = row;
startC = i;
}
//first char matches
if(sample.length - 1 == index) {
endR = row;
endxC = i;
wordFound = true;
SSystem.out.println("Word found at [" + startR + "][" + startC + "] & ["
+ endR + "][" + endC + "]");
break;
}
index++;
}
row--;
}
}
谢谢你!
答案 0 :(得分:0)
要找出4个对角线单词,我会尝试遵循
找到所有4个对角词的工作代码
public class Main {
public static void main(String[] args) {
char[][] testData = {{'a', 'b', 'c', 'd'}, {'e', 'c', 'b', 'e'}, {'h', 'g', 'a', 'm'}, {'w', 'x', 'z', 't'}};
char[] sample = {'c', 'a', 't'};
boolean result = findInDiagonalWords(diagonalWords(testData),sample);
System.out.println(result);
}
private static List<String> diagonalWords(char[][] testData) {
String first = topLeftBottomRight(testData);
StringBuilder sb = new StringBuilder();
sb.append(first);
String second = sb.reverse().toString();
String third = bottomLeftTopRight(testData);
StringBuilder sb1 = new StringBuilder();
sb1.append(third);
String fourth = sb1.reverse().toString();
return Arrays.asList(first, second, third, fourth);
}
private static String topLeftBottomRight(char[][] testData) {
String topLeftBottomRight = "";
for (int i = 0; i < testData.length; i++) {
for (int j = 0; j <= i; j++) {
if (i == j) {
topLeftBottomRight = topLeftBottomRight + testData[i][j];
}
}
}
return topLeftBottomRight;
}
private static String bottomLeftTopRight(char[][] testData) {
String bottomLeftTopRight = "";
for (int i = testData.length; i > 0; i--) {
for (int j = 0; j < testData.length; j++) {
if ((testData.length - i) == j) {
bottomLeftTopRight = bottomLeftTopRight + testData[i - 1][j];
break;
}
}
}
return bottomLeftTopRight;
}
private static boolean findInDiagonalWords(List<String> diagonalWords, char[] sample) {
// return true if sample lies in diagonal words
//return false;
}
}