class Solution {
public:
int m,n;
vector<vector<char>> board;
string word;
vector<vector<bool>>record;
bool exist(vector<vector<char>>& _board, string _word) {
board=_board; word= _word;
m= board.size(),n=board[0].size();
record=vector<vector<bool>>(m,vector<bool>(n,false));
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
if( board[i][j]== word[0])
if(dfs(i,j,1))return true;
return false;
}
bool dfs(int x,int y,int u)
{
if(u== word.size())return true;
int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};
record[x][y]=true;
for(int i=0;i<4;i++)
{
int a=x+dx[i],b=y+dy[i];
if(a>=0 && a<m && b>=0 && b<n && !record[a][b] && board[a][b]== word[u])
{
if(dfs(a,b,u+1))return true;
}
}
record[x][y]=false;//搜不到就恢复现场
return false;
}
};
leetcode 79. 单词搜索
最新推荐文章于 2025-04-01 21:46:03 发布