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:
    bool search(vector<vector<char>>& board, vector<vector<bool>> &flag, int x, int y, string &word, int start){
        int m = board.size();
        int n = board[0].size();
        if(start == word.length())
            return true;
        if(x < 0 || x >= m || y < 0 || y >= n || flag[x][y] || word.at(start) != board[x][y])
            return false;
        flag[x][y] = true;
        bool ans = search(board, flag, x+1, y, word, start+1) ||
                    search(board, flag, x-1, y, word, start+1) ||
                    search(board, flag, x, y+1, word, start+1) ||
                    search(board, flag, x, y-1, word, start+1);
        flag[x][y] = false;
        return ans;
    }
    bool exist(vector<vector<char>>& board, string word) {
        int m = board.size();
        if(m == 0)
            return false;
        int n = board[0].size();
        vector<vector<bool> > flag(m, vector<bool> (n, false));
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                    if(search(board, flag, i, j, word, 0))
                        return true;
            }
        }
        return false;
    }
};