YunheWang0813
10/30/2019 - 6:08 AM

0079. Word Search

class Solution {
public:
    bool exist(vector<vector<char>>& board, string word) {
        for (int i = 0; i < board.size(); i++) {
            for (int j = 0; j < board[0].size(); j++) {
                if (exist(board, word, i, j, 0)) return true;
            }
        }
        return false;
    }
    bool exist(vector<vector<char>>& board, string word, int i, int j, int idx) {
        if (idx >= word.size()) return true;
        if (i < 0 || i >= board.size() || j < 0 || j >= board[0].size()) return false;
        if (board[i][j] == word[idx++]) {
            char c = board[i][j];
            board[i][j] = '#';
            bool res = exist(board, word, i + 1, j, idx) ||
                       exist(board, word, i - 1, j, idx) ||
                       exist(board, word, i, j + 1, idx) ||
                       exist(board, word, i, j - 1, idx);
            board[i][j] = c;
            return res;
        }
        return false;
    }
};