题目链接:https://leetcode-cn.com/problems/word-search/
题目如下:
class Solution {
public:
int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};
bool res=false;
vector<vector<char>> g;
bool exist(vector<vector<char>>& board, string word) {
g=board;
for(int i=0;i<board.size();i++){
for(int j=0;j<board[i].size();j++){
if(word[0]==board[i][j]) dfs(i,j,1,word);
}
}
return res;
}
void dfs(int x,int y,int start,string& word){
if(start==word.size()) {res=true;return;}
char temp=g[x][y];
g[x][y]='.';
for(int i=0;i<4;i++){
int a=x+dx[i],b=y+dy[i];
if(a>=0&&a<g.size()&&b>=0&&b<g[0].size()&&g[a][b]!='.') {
if(g[a][b]==word[start]) dfs(a,b,start+1,word);
}
}
g[x][y]=temp;
}
};
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)