leetcode 79. Word Search【dfs找方格中出现字符串】
https://leetcode.com/problems/word-search/description/
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
Example:
board = [ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ] Given word = "ABCCED", return true. Given word = "SEE", return true. Given word = "ABCB", return false.
简单的dfs 都忘记回溯要更改回原来的状态的
class Solution {
public:
bool dfs(vector<vector<char> > &board,string word,int x,int y,int k){
// printf("x=%d,y=%d,k=%d,board[][]=%c,word=%c\n",x,y,k,board[x][y],word[k]);
if(k==word.size()-1)
return true;
int n=board.size();
int m=board[0].size();
char tmp=board[x][y];
board[x][y]='#';
if((x+1<n&&board[x+1][y]==word[k+1]&&dfs(board,word,x+1,y,k+1))
||(y-1>=0&&board[x][y-1]==word[k+1]&&dfs(board,word,x,y-1,k+1))
||(y+1<m&&board[x][y+1]==word[k+1]&&dfs(board,word,x,y+1,k+1))
||(x-1>=0&&board[x-1][y]==word[k+1]&&dfs(board,word,x-1,y,k+1)))
return true;
board[x][y]=tmp;
return false;
}
bool exist(vector<vector<char>>& board, string word) {
int n=board.size();
int m=board[0].size();
bool flag=false;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(board[i][j]==word[0]&&dfs(board,word,i,j,0))
return true;
}
}
return false;
}
};
查看6道真题和解析