-
Notifications
You must be signed in to change notification settings - Fork 0
/
word-search.java
36 lines (27 loc) · 954 Bytes
/
word-search.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution {
public boolean exist(char[][] board, String word) {
for(int i =0;i<board.length;i++)
{
for(int j =0;j<board[i].length;j++)
{
if(dfs(board,word,i,j,0))
return true;
}
}
return false;
}
private boolean dfs(char [][] board,String word,int i , int j , int step)
{
if(step==word.length())
return true;
if(i<0||i>=board.length||j>=board[i].length||j<0)
return false;
if((board[i][j]- word.charAt(step))!=0)
return false;
char record=board[i][j];
board[i][j]='1';
boolean answer=dfs(board,word,i+1,j,step+1)||dfs(board,word,i-1,j,step+1)||dfs(board,word,i,j+1,step+1)||dfs(board,word,i,j-1,step+1);
board[i][j]=record;
return answer;
}
}