-
Notifications
You must be signed in to change notification settings - Fork 0
/
LC79wordSearch.cpp
51 lines (48 loc) · 1.76 KB
/
LC79wordSearch.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
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
vector<vector<bool>> visited;
for (int i = 0; i < board.size(); i++) {
vector<bool> temp(board[i].size(), false);
visited.push_back(temp);
}
return exist(board, word, visited);
}
private:
bool exist(vector<vector<char>>& board, string word,
vector<vector<bool>>& visited) {
if (word.empty()) return true;
for (int i = 0; i < board.size(); i++) {
for (int j = 0; j < board[i].size(); j++) {
if (board[i][j] == word[0] &&
findNext(board, word.substr(1), i, j, visited))
return true;
}
}
return false;
}
bool findNext(vector<vector<char>>& board, string word, int x, int y,
vector<vector<bool>>& visited) {
if (word.empty()) return true;
visited[x][y] = true;
if (y < board[x].size() - 1 && !visited[x][y + 1] &&
board[x][y + 1] == word[0] &&
findNext(board, word.substr(1), x, y + 1, visited))
return true;
if (y > 0 && !visited[x][y - 1] && board[x][y - 1] == word[0] &&
findNext(board, word.substr(1), x, y - 1, visited))
return true;
if (x < board.size() - 1 && !visited[x + 1][y] &&
board[x + 1][y] == word[0] &&
findNext(board, word.substr(1), x + 1, y, visited))
return true;
if (x > 0 && !visited[x - 1][y] && board[x - 1][y] == word[0] &&
findNext(board, word.substr(1), x - 1, y, visited))
return true;
visited[x][y] = false;
return false;
}
};