Friday, July 21, 2017

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 =
[
  ['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 dfs(vector<vector<char>>& board, vector<vector<bool>>& visited,
             int i, int j, string word, int start) {          
        if (start == word.size()) {
            return true;
        }    
        if (i < 0 || i >= board.size() || j < 0 || j >= board[0].size() ||
            visited[i][j] || board[i][j] != word[start]) {
            return false;
        }
     
        visited[i][j] = true;
        bool ans = dfs(board, visited, i + 1, j, word, start + 1) ||
                   dfs(board, visited, i, j + 1, word, start + 1) ||
                   dfs(board, visited, i, j - 1, word, start + 1) ||
                   dfs(board, visited, i - 1, j, word, start + 1);
        if (ans == true) {
            return ans;
        }
        visited[i][j] = false;
        return false;
     
    }
 
    bool exist(vector<vector<char>>& board, string word) {
        bool ans = false;
        if (word.empty()) {
            return ans;
        }
        int row = board.size();
        int col = (board.size() != 0 ? board[0].size() : 0);
     
        vector<vector<bool>> visited(row, vector<bool>(col, false));
     
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                ans = dfs(board, visited, i, j, word, 0);
                if (ans) {
                    return true;
                }
            }
        }
        return false;
    }
};



=============== Faster if don't used visited matrix, instead use the same board =========
char letter = board[ y ][ x ]; board[ y ][ x ] = '*'; bool success = DFS( board, y, x + 1, word, index + 1 ) || DFS( board, y, x - 1, word, index + 1 ) || DFS( board, y + 1, x, word, index + 1 ) || DFS( board, y - 1, x, word, index + 1 ); board[ y ][ x ] = letter;

No comments:

Post a Comment