Repository navigation
Expand file tree
/
Copy path079_Word_Search.cpp
More file actions
55 lines (51 loc) · 1.67 KB
/
Copy path079_Word_Search.cpp
File metadata and controls
55 lines (51 loc) · 1.67 KB
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
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
const int m = board.size(), n = board[0].size();
bool ret = false;
for(int i = 0; i < m; ++i)
for(int j = 0; j < n; ++j)
if(board[i][j] == word[0]) {
ret = BFS(board, word, i, j, 0);
if(ret)
return ret;
}
else
continue;
return ret;
}
bool BFS(vector<vector<char>>& board, const string &word, const int &x, const int &y, const int &word_idx) {
if(word_idx == word.size() - 1)
return true;
const int m = board.size(), n = board[0].size();
typedef pair<int, int> state_t;
queue<state_t> q;
bool ret = false;
auto state_is_valid = [&](const state_t &t) {
const int x = t.first, y = t.second;
if(x < 0 || x >= m || y < 0 || y >= n || board[x][y] != word[word_idx + 1])
return false;
return true;
};
auto state_expand = [&]() {
state_t ex[4] = {{x - 1, y}, {x + 1, y}, {x, y - 1}, {x, y + 1}};
for(int i = 0; i < 4; ++i) {
if(state_is_valid(ex[i]))
q.push(ex[i]);
}
};
state_expand();
auto tmp = board[x][y];
board[x][y] = 0;
while(!q.empty()) {
auto k = q.front();
q.pop();
if((ret |= BFS(board, word, k.first, k.second, word_idx + 1)))
break;
else
continue;
}
board[x][y] = tmp;
return ret;
}
};