Skip to content

Commit f510d30

Browse files
committed
Time: 168 ms (74.30%), Space: 7.3 MB (36.77%) - LeetHub
1 parent a13aa71 commit f510d30

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

word-search/word-search.cpp

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
class Solution {
2+
public:
3+
int dx[4] = {0, 0, 1, -1};
4+
int dy[4] = {1, -1, 0, 0};
5+
6+
bool dfs(int i, int j, int idx, const string& word, vector<vector<char>>& board){
7+
int n = board.size();
8+
int m = board[0].size();
9+
10+
int len = word.size();
11+
if(idx == len - 1){
12+
return board[i][j] == word[idx];
13+
}
14+
15+
if (board[i][j] != word[idx])
16+
return false;
17+
18+
19+
char old = board[i][j];
20+
board[i][j] = '0';// visited
21+
22+
for(int k = 0; k < 4; k++){
23+
int r = i + dx[k];
24+
int c = j + dy[k];
25+
26+
if(r < 0 or r >= n or c < 0 or c >= m or board[r][c] == '0')
27+
continue;
28+
29+
if (dfs(r, c, idx + 1, word, board))
30+
return true;
31+
}
32+
33+
board[i][j] = old;// undo & backtrack
34+
return false;
35+
}
36+
37+
bool exist(vector<vector<char>>& board, string word) {
38+
int n = board.size();
39+
int m = board[0].size();
40+
int len = word.size();
41+
42+
43+
for(int i = 0; i < n; i++){
44+
for(int j = 0; j < m; j++){
45+
if(board[i][j] == word[0]){
46+
if(dfs(i, j, 0, word, board))
47+
return true;
48+
}
49+
}
50+
}
51+
52+
return false;
53+
}
54+
};

0 commit comments

Comments
 (0)