Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where “adjacent” cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
For example,
[
["ABCE"],
["SFCS"],
["ADEE"]
]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.
[code]
public class Solution {
public boolean exist(char[][] board, String word) {
if(word==null || word.equals(""))return true;
if(board==null || board.length==0 || board[0].length==0)return false;
int m=board.length, n=board[0].length;
char [] cs=word.toCharArray();
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(board[i][j]==cs[0])
{
if(dfs(i,j,board,0,cs))return true;
}
}
}
return false;
}
boolean dfs(int row, int col, char[][]board, int index, char[]cs)
{
if(index==cs.length)return true;
if(row<0 || row>=board.length || col<0 || col>=board[0].length || board[row][col]=='.')return false;
if(board[row][col]==cs[index])
{
board[row][col]='.';
if(dfs(row+1, col, board, index+1, cs))return true;
if(dfs(row-1, col, board, index+1, cs))return true;
if(dfs(row,col+1, board, index+1, cs))return true;
if(dfs(row, col-1, board, index+1, cs))return true;
board[row][col]=cs[index];
}
return false;
}
}
[Thoughts]
dfs, bfs 都不要忘了mark visited过的nodes