-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path79.word-search.cpp
62 lines (50 loc) · 1.33 KB
/
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
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
/*
* @lc app=leetcode id=79 lang=cpp
*
* [79] Word Search
*/
// @lc code=start
#include <algorithm>
#include <iostream>
#include <memory.h>
#include <stack>
#include <unordered_map>
#include <utility>
#include <vector>
using namespace std;
int rowCnt;
int colCnt;
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
rowCnt = board.size();
colCnt = board[0].size();
for (int i = 0; i < board.size(); ++i) {
for (int j = 0; j < board[0].size(); ++j) {
if (dfs(board, word, i, j, 0))
return true;
}
}
return false;
}
bool dfs (vector<vector<char>>& board, string& word, int row, int col, int index) {
if (index >= word.size()) {
return true;
}
if (row < 0 || row == rowCnt || col < 0 || col == colCnt || board[row][col] != word[index])
{
return false;
}
bool ret = false;
board[row][col] = '#';
int rowOffsets[] = { 0, 1, 0, -1 };
int colOffsets[] = { 1, 0, -1, 0 };
for (int d = 0; d < 4; ++d) {
ret = dfs(board, word, row + rowOffsets[d], col + colOffsets[d], index + 1);
if (ret) break;
}
board[row][col] = word[index];
return ret;
}
};
// @lc code=end