Loading

【leetcode】79. Word Search

  Given an m x n grid of characters board and a string word, return true if word exists in the grid. The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
       
class Solution {
public:
    bool dfs(vector<vector<char>>& board,string word,int i,int j,int n){
        //递归终止条件
        if(n==word.size()) return true;
        if(i<0 || j<0 || i>=board.size()||j>=board[0].size() || board[i][j]!=word[n]) return false;
        board[i][j]='0';//这个位置检索到了
        bool flag=(dfs(board,word,i+1,j,n+1) || dfs(board,word,i-1,j,n+1)||
                  dfs(board,word,i,j+1,n+1)|| dfs(board,word,i,j-1,n+1));
        board[i][j]=word[n];
        return flag;

    }
    bool exist(vector<vector<char>>& board, string word) {
        //深度优先递归回溯
        if(word=="") return false;
        int m=board.size(),n=board[0].size();
        for(int i=0;i<m;++i){
            for(int j=0;j<n;++j){
                if(dfs(board,word,i,j,0)) return true;
            }
        }
        return false;
    }
};

 

posted @ 2021-11-19 16:53  aalanwyr  阅读(35)  评论(0编辑  收藏  举报