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 =

[ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ] word = "ABCCED", -> returns true, word = "SEE", -> returns true, word = "ABCB", -> returns false.

class Solution {
public:
    bool exist(vector<vector<char> > &board, string word) {
        if (word.empty()) return true;
        if (board.empty() || board[0].empty()) return false;
        vector<vector<bool> > visited(board.size(), vector<bool>(board[0].size(), false));
        for (int i = 0; i < board.size(); ++i) {
            for (int j = 0; j < board[i].size(); ++j) {
                if (search(board, word, 0, i, j, visited)) return true;
            }
        }
        return false;
    }
    bool search(vector<vector<char> > &board, string word, int idx, int i, int j, vector<vector<bool> > &visited) {
        if (idx == word.size()) return true;
        if (i < 0 || j < 0 || i >= board.size() || j >= board[0].size() || visited[i][j] || board[i][j] != word[idx]) return false;
        visited[i][j] = true;
        bool res = search(board, word, idx + 1, i - 1, j, visited) 
                 || search(board, word, idx + 1, i + 1, j, visited)
                 || search(board, word, idx + 1, i, j - 1, visited)
                 || search(board, word, idx + 1, i, j + 1, visited);
        visited[i][j] = false;
        return res;
    }
};
class Solution {
    public boolean exist(char[][] board, String word) {
        boolean[][]visited = new boolean[board.length][board[0].length];
        for(int i = 0; i<board.length;++i){
            for(int j = 0;j<board[0].length;++j){
                    if(dfs(board,visited,word,0,i,j)) return true;
            }
        }
        return false;
    }
    boolean dfs(char[][] board, boolean[][]visited,String word, int index,int row, int col){
        if(word.length() == index) return true;
        if(row<0||row>=board.length||col<0||col>=board[0].length||visited[row][col]) return false;
        if(board[row][col]!=word.charAt(index)) return false;
        visited[row][col] = true;
        boolean existed= dfs(board,visited,word,index+1,row-1,col) ||dfs(board,visited,word,index+1,row+1,col)||dfs(board,visited,word,index+1,row,col+1)||dfs(board,visited,word,index+1,row,col-1);
        visited[row][col] = false;
        return existed;

    }
}

REF:

results matching ""

    No results matching ""