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;
    }
};

 

全部评论

相关推荐

对空六翼:你真幸运,碰见这么好的人,不像我,秋招的时候被室友骗进cx了
实习好累,可以辞职全力准...
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
正在热议
更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务