Leetcode 79. 单词搜索
题目
给定一个二维网格和一个单词,找出该单词是否存在于网格中。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
测试样例
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
给定 word = "ABCCED", 返回 true
给定 word = "SEE", 返回 true
给定 word = "ABCB", 返回 false
提示
- board 和 word 中只包含大写和小写英文字母。
- 1 <= board.length <= 200
- 1 <=board[i].length <= 200
- 1 <= word.length <= 10^3
题解
回溯算法
选择当前可以走的方向,如果当前单词搜索到便可以停止搜索,详细过程见代码
代码
int m,n;
vector<vector<int>> use;
int dir[4][2] = {{-1,0},{0,1},{1,0},{0,-1}};
bool dfs(int now,int x,int y,vector<vector<char>> &board,string& word){
int i,j;
if(now == word.length()) return true;
else{
int newx,newy;
for(int i=0; i<4; i++){
newx = x+dir[i][0];
newy = y+dir[i][1];
if(newx>=0 && newx<m && newy>=0 && newy<n && !use[newx][newy] && board[newx][newy]==word[now]){
use[newx][newy] = 1;
if(dfs(now+1,newx,newy,board,word)) return true;
use[newx][newy] = 0;
}
}
}
return false;
}
bool exist(vector<vector<char>>& board, string word) {
m =board.size(),n=board[0].size();
use = vector<vector<int>>(m,vector<int>(n,0));
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if(board[i][j] == word[0]){
use[i][j] = 1;
if(dfs(1,i,j,board,word)) return true;
use[i][j] = 0;
}
}
}
return false;
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/word-search
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。