-
Notifications
You must be signed in to change notification settings - Fork 0
/
79. Word Search.cpp
36 lines (34 loc) · 911 Bytes
/
79. Word Search.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
#include<vector>
using namespace std;
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
if (board.size() == 0 || board[0].size() == 0)
return true;
for (int i = 0; i<board.size(); i++) {
for (int j = 0; j<board[0].size(); j++) {
if (board[i][j] == word[0])
if (check(board, word.substr(1), i, j))
return true;
}
}
return false;
}
bool check(vector<vector<char>>& board, string word, int i, int j) {
if (word.length() == 0)
return true;
if (i<0 || j<0 || i >= board.size() || j >= board[0].size())
return false;
if (word[0] == board[i][j]) {
char c = word[0];
board[i][j] = '\0';
if (check(board, word.substr(1), i + 1, j) ||
check(board, word.substr(1), i - 1, j) ||
check(board, word.substr(1), i, j + 1) ||
check(board, word.substr(1), i, j - 1))
return true;
board[i][j] = c;
}
return false;
}
};