/*
* @lc app=leetcode id=79 lang=cpp
*
* [79] Word Search
*/
// @lc code=start
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
if(word.length() <= 0) return true;
int N = board.size();
if(N == 0) return false;
int M = board[0].size();
if(M == 0) return false;
vector<vector<int>> flag(N,vector<int>(M,0));
vector<int> dirx = {-1,1,0,0};
vector<int> diry = {0,0,-1,1};
for(int i=0;i<N;i++){
for(int j=0;j<M;j++){
if(board[i][j] == word[0]){
if(dfs(i,j,1,flag,word,board,dirx,diry,N,M)) return true;
}
}
}
return false;
}
bool dfs(int x,int y,int loc,
vector<vector<int>>& flag,
string& word,
vector<vector<char>>& board,
vector<int>& dirx,
vector<int>& diry,
int& N,int& M)
{
if(loc == word.size()) return true;
flag[x][y] = 1;
int xx,yy;
for(int i=0;i<4;i++){
xx = x+dirx[i];
yy = y+diry[i];
if( xx >= 0 && xx < N && yy >= 0 && yy < M){
if(board[xx][yy] == word[loc] && !flag[xx][yy]){
if(dfs(xx,yy,loc+1,flag,word,board,dirx,diry,N,M)) return true;
}
}
}
flag[x][y] = 0;
return false;
}
};
// @lc code=end
No.219 - LeetCode[79] Word Search - 字母矩阵中找单词 - 经典四向dfs
最新推荐文章于 2024-08-10 22:52:22 发布