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:
    typedef vector<vector<bool> > VVB;
    typedef vector<vector<char> > VVC;
    
    const int dx[4] = {0,1,0,-1};
    const int dy[4] = {1,0,-1,0};
    
    int n,m;
    VVC board;
    string word;
    
    bool dfs(int x, int y,int index,VVB &visit){
        if(index == word.length()) return true;
        if(x>=0 && x <n && y>=0 && y < m && !visit[x][y] && board[x][y] == word[index]){
            visit[x][y] = true;
            for(int i = 0 ; i < 4; ++ i){
                if(dfs(x+dx[i], y+dy[i],index+1,visit)) return true;
            }
            visit[x][y] = false;
        }
        return false;
    }

    bool exist(VVC &board, string word) {
        this->board = board;
        this->word = word;
        n = board.size();
        m = board[0].size();
        VVB visit(n,vector<bool>(m,false));
        for(int i = 0 ; i < n; ++i ){
            for(int j = 0 ; j < m ;++ j){
                if(dfs(i,j,0,visit)) return true;
            }
        }
        return false;
    }
};
原文地址:https://www.cnblogs.com/xiongqiangcs/p/3826258.html