[LeetCode] Word Search

2183 ワード

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 .
問題解決の考え方:
遡及法1つの2次元配列でアクセスしたかどうかをマークし、上下左右の4つの方向に拡張すればよい.
class Solution {
public:
    bool exist(vector<vector<char>>& board, string word) {
        int len = word.length();
        if(len==0){
            return true;
        }
        int m = board.size();
        if(m==0){
            return false;
        }
        int n = board[0].size();
        if(n==0){
            return false;
        }
        vector<vector<bool>> flag(m, vector<bool>(n, false));
        for(int i=0; i<m; i++){
            for(int j=0; j<n; j++){
                if(helper(board, flag, i, j, 0, word)){
                    return true;
                }
            }
        }
        return false;
    }
    
    bool helper(vector<vector<char>>& board, vector<vector<bool>>& flag, int i, int j, int index, string& word){
        if(index>=word.length()){
            return true;
        }
        int m = board.size();
        int n = board[0].size();
        if(i<0 || i>=m || j<0 || j>=n || flag[i][j] || board[i][j]!=word[index]){
            return false;
        }
        flag[i][j] = true;
        bool result = helper(board, flag, i+1, j, index + 1, word) ||
                      helper(board, flag, i, j+1, index + 1, word) ||
                      helper(board, flag, i-1, j, index + 1, word) ||
                      helper(board, flag, i, j-1, index + 1, word);
        flag[i][j] = false;
        return result;
    }
};