首页 > 代码库 > LeetCode Word Search

LeetCode Word Search

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.

For example,
Given board =

[
  ["ABCE"],
  ["SFCS"],
  ["ADEE"]
]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,

word = "ABCB", -> returns false.

class Solution {
public:
    bool dfs(int depth,vector<vector<char> >&board,string word,int x,int y){
        if(depth==word.size())
        {
            return true;
        }
        else if(x>=board.size()||x<0)return false;
        else if(y>=board[0].size()||y<0)return false;
        else
        {
            if(board[x][y]==word[depth])
            {
                board[x][y]='.';
                if(dfs(depth+1,board,word,x+1,y))return true;
                if(dfs(depth+1,board,word,x,y+1))return true;
                if(dfs(depth+1,board,word,x-1,y))return true;
                if(dfs(depth+1,board,word,x,y-1))return true;
                board[x][y]=word[depth];
                return false;
            }
            else
                return false;
        }
    }
    bool exist(vector<vector<char> > &board, string word) {
        bool f=false;
        if(board.size()==0)return false;
        if(board[0].size()==0)return true;
        for(int i=0;i<board.size();++i)
            for(int j=0;j<board[0].size();++j)
            {
                if(dfs(0,board,word,i,j))
                    f=true;
            }
        //if(f==true)cout<<"true"<<endl;
        //else std::cout << "false" << std::endl;
        return f;
    }
};


LeetCode Word Search