79. Word Search

2018/05/13 leetcode 共 1216 字,约 4 分钟

title

link 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.

solution

class Solution {
public:
    bool dfs(vector<vector<char>>& board,vector<vector<bool>>& visit,int x,int y,string &word,int k){
        if(k==word.size()){
            return true;
        }
        if(x<0||x>=board.size()||y<0||y>=board[0].size()){
            return false;
        }
        if(visit[x][y])
            return false;
        if(board[x][y]!=word[k])
            return false;
        visit[x][y]=true;
        
        if(dfs(board,visit,x+1,y,word,k+1)) return true;
        if(dfs(board,visit,x,y+1,word,k+1)) return true;
        if(dfs(board,visit,x-1,y,word,k+1)) return true;
        if(dfs(board,visit,x,y-1,word,k+1)) return true;
        visit[x][y]=false;
        return false;

    }

    bool exist(vector<vector<char>>& board, string word) {
        int n=board.size();
        int m=board[0].size();
        vector<vector<bool>> visit(n,vector<bool>(m,false));
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                if(dfs(board,visit,i,j,word,0)) return true;
            }
        }
         return false;
    }
};

Search

    Table of Contents