-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlc79.cpp
More file actions
101 lines (79 loc) · 2.57 KB
/
lc79.cpp
File metadata and controls
101 lines (79 loc) · 2.57 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include <vector>
#include <map>
#include <string>
#include <iostream>
#include <algorithm>
#include <set>
#include <map>
#include <unordered_map>
#include <tuple>
using namespace std;
class Solution {
vector<vector<char>> _board;
string _word;
int m, n;
bool search(int r, int c, int p) {
if (_board[r][c] != _word[p]) return false;
if (p == _word.size() - 1) return true;
char save = _board[r][c];
_board[r][c] = '\0';
vector<pair<int,int>> adj = { {r-1,c}, {r+1,c}, {r,c-1}, {r,c+1} };
for(auto pos: adj) {
auto [r1,c1] = pos;
if (0 <= r1 && r1 < m && 0 <= c1 && c1 < n && _board[r1][c1] != '\0') {
if (search(r1,c1,p+1))
return true;
}
}
_board[r][c] = save;
return false;
}
public:
bool exist(vector<vector<char>>& board, string word) {
m = board.size();
n = board[0].size();
vector<pair<int,int>> start_positions;
_board = board;
_word = word;
// early exit
if ((int)word.size() > m * n) return false;
unordered_map<char,int> cnt;
for (auto &row: board)
for (char ch: row) cnt[ch]++;
for (char ch: word)
if (--cnt[ch] < 0)
return false;
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if (board[i][j] == word[0] && search(i,j,0))
return true;
}
}
return false;
}
};
int main() {
Solution s;
/*
vector<vector<char>> board = { {'Z','B','C','E'},
{'S','F','C','S'},
{'A','D','E','E'},
{'W','Z','Z','Z'}};
*/
/*
vector<vector<char>> board = {{'A','A','A','A','A','A'},
{'A','A','A','A','A','A'},
{'A','A','A','A','A','A'},
{'A','A','A','A','A','A'},
{'A','A','A','A','A','B'},
{'A','A','A','A','B','A'}};
*/
vector<vector<char>> board = {{'A','B','C','E'},
{'S','F','E','S'},
{'A','D','E','E'}};
//s.exist(board, "SEE");
//s.exist(board,"AAAAAAAAAAAAABB");
bool found = s.exist(board, "ABCESEEEFS");
if (found)
cout << "Solution found" << endl;
}