-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwordsearch.cpp
69 lines (51 loc) · 1.37 KB
/
wordsearch.cpp
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
int m, n;
// directions
vector<vector<int>> directions{{1,0},{-1,0},{0,1},{0,-1}};
bool find(vector<vector<char>>& board, int i, int j, int idx, string& word){
if(idx==word.size()) return true;
if(i<0 || j<0 || i>=m || j>=n || board[i][j]=='$') return false;
if(board[i][j]!=word[idx]) return false;
char temp = board[i][j];
board[i][j]='$';
for(auto &dir:directions){
int new_i = i+dir[0];
int new_j = j+dir[1];
if(find(board, new_i, new_j, idx+1, word)) return true;
}
board[i][j]=temp;
return false;
}
bool exist(vector<vector<char>>& board, string word) {
m = board.size();
n = board[0].size();
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
if(board[i][j]==word[0] && find(board, i, j, 0, word))
return true;
}
}
return false;
}
};
int main(){
vector<vector<char>> board = {
{'A','B','C','E'},
{'S','F','C','S'},
{'A','D','E','E'}
};
string word = "ABCCED";
bool ans;
Solution obj;
ans = obj.exist(board, word);
cout << ans << endl;
return 0;
}
// TC: O(M*N*3^L)
// SC: O(L)