leetcode Word Search

最简单的思路:

  • 将矩阵中的每个点当做起始点判断,是否可以从这一点开始,找到一条路径
class Solution {
public:
    bool isFound(int x, int y, vector<vector<char>> board, string word, int c)
    {
        if(x<0||y<0||x==board.size()||y==board[0].size())
            return false;
       // cout<<x<<"  "<<y<<endl;
        
       // cout<<board[x][y]<<"  "<<word[c]<<endl;
        if(board[x][y]==word[c])
        {
            board[x][y]='0';
            if (c+1==word.size())
            return true;
            return (isFound(x-1,y,board, word, c+1)||isFound(x,y-1,board, word, c+1)||isFound(x+1,y, board, word,c+1)||isFound(x,y+1, board, word, c+1));
        }

        else
            return false;
    }
    bool exist(vector<vector<char>>& board, string word) {
      int i=0,j=0;
        int c=0;
        bool is;
        for(int i=0;i<board.size();i++)
            for(int j=0;j<board[0].size();j++)
            {
                if(board[i][j]==word[0])
                {
                is= isFound(i,j,board,word,0);
                if(is)
                     return true;
                }

            }
        return false;

    }
};

 这一思路也可以利用深度优先搜索实现,将每一个点生成一个树,判断是否有解:

 

class Solution {
public:
    bool exist(const vector<vector<char>>& board, const string& word) {
        const int M=board.size(), N=board[0].size();
        vector<vector<bool>> occupy(M,vector<bool>(N,false));
        for (int i=0; i<M; ++i)
            for (int j=0; j<N; ++j)
                if(DFS(board,word,0,i,j,occupy))
                    return true;
        return false;
    }
    
private:
    static bool DFS(const vector<vector<char>>& board, const string& word, int start, int r, int c, vector<vector<bool>>& occupy){
        if (start==word.size())
            return true;
        if (r<0 || r>=board.size() || c<0 || c>=board[0].size())
            return false;
        if (occupy[r][c])
            return false;
        if (board[r][c]!=word[start])
            return false;
        
        
        occupy[r][c]=true;
        bool ret  =DFS(board,word,start+1,r-1,c,occupy) ||
                    DFS(board,word,start+1,r+1,c,occupy) ||
                    DFS(board,word,start+1,r,c-1,occupy) ||
                    DFS(board,word,start+1,r,c+1,occupy);
        occupy[r][c]=false;
        
        return ret;
    }
};

  

原文地址:https://www.cnblogs.com/fanhaha/p/7392691.html