79. Word Search

79. Word Search

class Solution {
public:
    bool exist(vector>& board, string word) {
        if(board.size()==0 || board[0].size()==0)
            return false;
        vector> dir{{0,-1},{0,1},{-1,0},{1,0}};
        int row=board.size(),col=board[0].size();
        vector> visited(row,vector(col,0));
        int index=0;
        for(int i=0;i>& board, string &word,vector> &dir,vector> &visited){
        if(index==word.size())
            return true;
        for(int i=0;i<4;i++){
            int curx=x+dir[i][0];
            int cury=y+dir[i][1];
            if(curx<0 || curx>=board.size() || cury<0 || cury>=board[0].size())        
                continue;                           //判断越界!!!
            if(visited[curx][cury]==0){
                if(word[index]==board[curx][cury]){
                    index++;
                    visited[curx][cury]=1;
                    if(DFS(index,curx,cury,board,word,dir,visited))
                        return true;
                    visited[curx][cury]=0;
                    index--;
                }
            }
        }
        return false;
    }
};

你可能感兴趣的:(Leetcode)