File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed
Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public:
3+ vector<vector<char >> g_board;
4+ int m, n;
5+ int dx[4 ] = { -1 , 1 , 0 , 0 };
6+ int dy[4 ] = { 0 , 0 , -1 , 1 };
7+ bool visited[6 ][6 ];
8+
9+ bool hasWord (string word, int idx, int r, int c) {
10+ if (idx >= word.size ()) return true ;
11+ if (!(0 <= r && r < n && 0 <= c && c < m)) return false ;
12+ if (g_board[r][c] != word[idx]) return false ;
13+ if (visited[r][c]) return false ;
14+ visited[r][c] = true ;
15+ // cout << r << " " << c << " " << word[idx] << "\n";
16+ for (int i = 0 ; i < 4 ; i++) {
17+ int nr = r + dx[i];
18+ int nc = c + dy[i];
19+ if (hasWord (word, idx+1 , nr, nc))
20+ return true ;
21+ }
22+ visited[r][c] = false ;
23+ return false ;
24+ }
25+
26+ bool exist (vector<vector<char >>& board, string word) {
27+ g_board = board;
28+ n = board.size ();
29+ m = board[0 ].size ();
30+ for (int i = 0 ; i < n; i++) {
31+ for (int j = 0 ; j < m; j++) {
32+ if (g_board[i][j] == word[0 ]) {
33+ fill (&visited[0 ][0 ], &visited[0 ][0 ]+36 , false );
34+ if (hasWord (word, 0 , i, j)) return true ;
35+ }
36+ }
37+ }
38+ return false ;
39+ }
40+ };
You can’t perform that action at this time.
0 commit comments