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,
Given board =
[ ["ABCE"], ["SFCS"], ["ADEE"] ]
word = "ABCCED"
, -> returns true
,
word = "SEE"
, -> returns true
,
word = "ABCB"
, -> returns false
.
</pre><pre name="code" class="java">public class Solution {
public static int dir[][]={{0,1},{1,0},{-1,0},{0,-1}};
static int[][] visit;
static boolean flag;
public boolean exist(char[][] board, String word) {
int row=board.length;
int col=board[0].length;
if(word.length()==0)
return true;
if(row*col<word.length())
return false;
visit=new int[row][col];
flag=false;
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
if(board[i][j]==word.charAt(0))
{
visit[i][j]=1;
search(i, j, board, word, 0);
visit[i][j]=0;
}
if(flag)
return true;
}
}
if(flag)
return true;
return false;
}
public void search(int row, int col, char[][] board, String word, int len)
{
if(flag)
return;
if(board[row][col]!=word.charAt(len))
return;
if(len==word.length()-1)
{
flag=true;
return;
}
for(int i=0;i<4;i++)
{
row+=dir[i][0];
col+=dir[i][1];
if(row>=0&&row<board.length&&col>=0&&col<board[0].length){
if(visit[row][col]==0)
{
visit[row][col]=1;
search(row,col,board,word,len+1);
visit[row][col]=0;
}
}
row-=dir[i][0];
col-=dir[i][1];
}
}
}