-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path79.cpp
More file actions
28 lines (28 loc) · 958 Bytes
/
79.cpp
File metadata and controls
28 lines (28 loc) · 958 Bytes
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
class Solution {//O(n*4^l)
public:
bool dfs(vector<vector<char>>& board, int i, int j, string& word, int idx){
if(idx==word.size())
return true;
if(idx>word.size() || i>=board.size() || i<0 || j>=board[0].size() || j<0 || word[idx]!=board[i][j])
return false;
char tmp = board[i][j];
board[i][j] = '.';
if(dfs(board,i,j+1,word,idx+1))
return true;
if(dfs(board,i+1,j,word,idx+1))
return true;
if(dfs(board,i,j-1,word,idx+1))
return true;
if(dfs(board,i-1,j,word,idx+1))
return true;
board[i][j] = tmp;
return false;
}
bool exist(vector<vector<char>>& board, string word) {
for(int i=0; i<board.size(); i++)
for(int j= 0; j<board[0].size(); j++)
if(word[0]==board[i][j] && dfs(board,i,j,word,0))
return true;
return false;
}
};