-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlc-212.cpp
More file actions
79 lines (61 loc) · 2.65 KB
/
lc-212.cpp
File metadata and controls
79 lines (61 loc) · 2.65 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
/*
Given a 2D board and a list of words from the dictionary, find all words in the board.
Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
Example:
Input:
words = ["oath","pea","eat","rain"] and board =
[
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']
]
Output: ["eat","oath"]
Note:
You may assume that all inputs are consist of lowercase letters a-z.
*/
class Solution {
public:
bool findUtil(vector<vector<char>> & board, const string & word, int index,
int row, int col,
int numRows, int numCols, vector<vector<bool>> & visited){
if (index == word.length()){
return true;
}
//cout<<row<<" "<<col<<endl;
if (row < 0 || row >= numRows || col < 0 || col >= numCols || visited[row][col]) return false;
if (board[row][col] == word[index]){
visited[row][col] = true;
if ( findUtil(board, word, index+1, row-1, col, numRows, numCols, visited) ||
findUtil(board, word, index+1, row+1, col, numRows, numCols, visited) ||
findUtil(board, word, index+1, row, col-1, numRows, numCols, visited) ||
findUtil(board, word, index+1, row, col+1, numRows, numCols, visited) ) {
return true;
}
visited[row][col] = false;
}
return false;
}
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
int numRows = board.size();
int numCols = board[0].size();
set<string> oSet;
for (int i = 0; i < words.size(); ++i){
vector<vector<bool> > visited(numRows,vector<bool>(numRows, false));
for (int row = 0; row < numRows; ++row){
for (int col = 0; col < numCols; ++col){
if (board[row][col] == words[i][0]){
//visited[row][col] = true;
if (findUtil(board, words[i], 0, row, col, numRows, numCols, visited)){
//output.push_back(words[i]);
oSet.insert(words[i]);
}
}
}
}
}
std::vector<string> output(oSet.size());
copy(oSet.begin(), oSet.end(), output.begin());
return output;
}
};