单词搜索
给定一个 m x n 二维字符网格 board 和一个字符串单词 word 。如果 word 存在于网格中,返回 true ;否则,返回 false 。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
示例 1:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
输出:true
示例 2:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
输出:true
示例 3:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
输出:false
提示:
m == board.length
n = board[i].length
1 <= m, n <= 6
1 <= word.length <= 15
board 和 word 仅由大小写英文字母组成
进阶:你可以使用搜索剪枝的技术来优化解决方案,使其在 board 更大的情况下可以更快解决问题?
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/word-search
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路
遍历整个board,dfs判断每个起点开始的board能否找到word,最主要的就是dfs的过程,还有就是尽量传引用,有些地方忘记传应用就导致了超时。剪枝优化以后再想想。
code
class Solution {
public:
int dx[4] = {-1,1,0,0};
int dy[4] = {0,0,-1,1};
int m,n;
bool dfs(vector<vector<char>>& board,int i,int j ,vector<vector<int>> & visit,string& word,int start)
{
if(start == word.size()) return true;
bool equal = (board[i][j] == word[start]);
visit[i][j] = 1;
if(!equal) return false;
if(start + 1 == word.size()) return equal;
bool next = false;
for(int k = 0;k < 4;k ++)
{
int x = i + dx[k];
int y = j + dy[k];
if(x >= 0 && x < m && y >= 0 && y < n && !visit[x][y])
{
visit[x][y] = 1;
next = next || dfs(board,x,y,visit,word,start + 1);
visit[x][y] = 0;
}
}
return next;
}
bool exist(vector<vector<char>>& board, string word) {
m = board.size(),n = board[0].size();
for(int i = 0;i < m;i ++)
{
for(int j = 0;j < n;j ++)
{
vector<vector<int>> visit(m,vector(n,0));
if(dfs(board,i,j,visit,word,0))
{
return true;
}
}
}
return false;
}
};
标签:word,int,visit,dfs,单词,搜索,board,return,79
From: https://www.cnblogs.com/huangxk23/p/17191658.html