Skip to content

Commit 04b7d0b

Browse files
committed
Create Word Search
1 parent 2d16a34 commit 04b7d0b

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

DFS/Word Search

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
一开始想到了一个大概,就是四领域按个去试,并且是以矩阵中的每一数作为起点都去试,然后结果没有想到递归的特性所以卡住了
2+
看了答案。。豁然。。
3+
4+
class Solution {
5+
private:
6+
bool check(vector<vector<char> > &board,string word,int i,int j,int index,vector<vector<bool>> &visited)
7+
{
8+
if(index == word.size())
9+
return true;
10+
if(i < 0 || j < 0 || i >= board.size()|| j >= board[0].size())
11+
return false;
12+
if(visited[i][j])
13+
return false;
14+
if(board[i][j] != word[index])
15+
return false;
16+
visited[i][j] = true;
17+
bool result = check(board,word,i+1,j,index+1,visited) ||check(board,word,i,j+1,index+1,visited)
18+
|| check(board,word,i-1,j,index+1,visited)|| check(board,word,i,j-1,index+1,visited); // 是或的关系,有四路,每路都有可能
19+
visited[i][j] = false;// 回退功能,此点下一次还可以被访问
20+
return result;
21+
}
22+
23+
public:
24+
bool exist(vector<vector<char> > &board, string word) {
25+
int n = board.size();
26+
int m = 0;
27+
if (n > 0)
28+
m = board[0].size();
29+
vector<vector<bool>> visited(n,vector<bool> (m,false));
30+
for (int i = 0;i < n;i++)
31+
for (int j = 0;j < m;j++)
32+
if(check(board,word,i,j,0,visited)) //以每一个数为起始去找寻可能的路径
33+
return true;
34+
return false;
35+
}
36+
37+
};

0 commit comments

Comments
 (0)