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.

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.
class Solution {
public:
    bool exist(vector>& board, string word) 
    {
        if(board.empty()||board[0].empty())
            return false;
        int n=board.size(),m=board[0].size();
        vector>  vis(n,vector(m,false));
        for(int i=0;i > &board,int x,int y,string word,int idx,
             vector > &vis)
    {
        if(idx==word.length())
            return true;
        if(x<0 ||x>=board.size()||y<0||y>=board[0].size()||vis[x][y]||
           board[x][y]!=word[idx])
            return false;
        vis[x][y]=true;
        bool ret=
        dfs(board,x+1,y,word,idx+1,vis)||
        dfs(board,x-1,y,word,idx+1,vis)||
        dfs(board,x,y+1,word,idx+1,vis)||
        dfs(board,x,y-1,word,idx+1,vis);
        vis[x][y]=false;
        return ret;
    }
};

你可能感兴趣的:(leetcode,DFS)