DFS Java AC
public class Solution {
private int m, n, len;
private int visit[][];
public boolean exist(char[][] board, String word) {
m = board.length;
n = board[0].length;
len = word.length();
if (len > m * n) {
return false;
}
visit = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (dfs(board, word, i, j, 0)) {
return true;
}
}
}
return false;
}
private boolean dfs(char board[][], String word,
int startx, int starty, int k) {
if(startx < 0 || startx >= m
|| starty < 0 || starty >= n
|| visit[startx][starty] == 1){
return false;
}
if(board[startx][starty] != word.charAt(k)){
return false;
}
if(k == len - 1){
return true;
}
visit[startx][starty] = 1;
boolean flag = dfs(board, word, startx - 1, starty, k + 1)
|| dfs(board, word, startx + 1, starty, k + 1)
|| dfs(board, word, startx, starty - 1, k + 1)
|| dfs(board, word, startx, starty + 1, k + 1);
visit[startx][starty] = 0;
return flag;
}
}
BFS Java TLE
public class Solution {
private int stepArr[][] = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };
private int m, n, len;
private int visit[][];
public boolean exist(char[][] board, String word) {
m = board.length;
n = board[0].length;
len = word.length();
if (len > m * n) {
return false;
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
visit = new int[m][n];
if (bfs(board, word, i, j, 0)) {
return true;
}
}
}
return false;
}
private boolean bfs(char board[][], String word, int nodei,
int nodej, int k) {
if (k >= len) {
return false;
}
if (board[nodei][nodej] != word.charAt(k)) {
return false;
}
if (k == len-1) {
return true;
}
Queue queue = new LinkedList();
Node node = new Node(nodei, nodej, k);
queue.offer(node);
visit[nodei][nodej] = 1;
while (!queue.isEmpty()) {
node = queue.peek();
queue.poll();
int newx = 0;
int newy = 0;
int newk = 0;
boolean flag = false;
for (int i = 0; i < 4; i++) {
newx = node.x + stepArr[i][0];
newy = node.y + stepArr[i][1];
newk = node.k + 1;
if (newx >= 0 && newx < m
&& newy >= 0 && newy < n
&& newk < len
&& visit[newx][newy] == 0
&& board[newx][newy] == word.charAt(newk)) {
flag = true;
if (newk == len - 1) {
return true;
}
visit[newx][newy] = 1;
queue.offer(new Node(newx, newy, newk));
}
}
if (!flag) {
return false;
}
}
return false;
}
public class Node {
int x;
int y;
int k;
Node(int x, int y, int k) {
this.x = x;
this.y = y;
this.k = k;
}
}
}