LeetCode--word search
package leetcode;
public class WordSearch2 {
public static int[] DX = { 0, 1, 0, -1 };
public static int[] DY = { 1, 0, -1, 0 };
public static boolean exist(char[][] board, String word) {
int m = board.length;
int n = board[0].length;
boolean[][] visited = new boolean[m][n]; // 初始都为0,都未读状态
for (int i = 0; i != m; i++) {
for (int j = 0; j != n; j++) {
if (board[i][j] == word.charAt(0)) {
if (word.length() == 1) {
return true;
}
visited[i][j] = true;
if (Vertify(board, visited, 0, i, j, word))
return true;
}
}
}
return false;
}
public static boolean Vertify(char[][] board, boolean[][] visited, int k, int x, int y, String word) {
for (int a = 0; a != 4; a++) {
int xx = x + DX[a];
int yy = y + DY[a];
if (xx < board.length && yy < board[0].length && yy >= 0 && xx >= 0) {
if (visited[xx][yy] == true)
continue;
if (board[xx][yy] == word.charAt(k)) {
visited[xx][yy] = true;
if (k == word.length()-1) // 难点:怎么去记录这个点是否走过,怎么用计数器记录操作过的字符?
return true;
else
Vertify(board, visited, k + 1, xx, yy, word); // 不用很了解回溯的过程!
} else {
visited[xx][yy] = false; // if/for等语句,找好其范围是关键,不要改程序的时候,将if管的范围给弄混乱!否则出现数组越界等等问题
// 改“{” 想到 “}”
}
}
}
return false;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
char[][] board = {{'C','A','A'},{'A','A','A'},{'B','C','D'}};
String word = "AAB";
System.out.println(exist(board, word));
}
}