79. Word Search

Posted The Tech Road

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了79. Word Search相关的知识,希望对你有一定的参考价值。

https://leetcode.com/problems/word-search/description/

class Solution {
public:
    int m, n;
    bool exist(vector<vector<char>>& board, string word) {
        m = board.size();   if (m == 0) return false;
        n = board[0].size();    if (n == 0) return false;
        if (word == "") return true;
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
                if (helper(board, word, 0, i, j))
                    return true;
        return false;
    }
    bool helper(vector<vector<char>>& board, const string& word, int start, int i, int j) {
        if (board[i][j] != word[start]) return false;
        if (start+1 == word.length()) return true;
        
        char c = board[i][j];
        board[i][j] = 0;
        int dirs[] = { -1, 0, 1, 0, -1 };
        for (int d = 0; d < 4; d++) {
            int x = i + dirs[d];
            int y = j + dirs[d+1];
            if (x >= 0 && x < m && y >= 0 && y < n && helper(board, word, start+1, x, y))
                return true;
        }
        board[i][j] = c;
        return false;
    }
};

 

以上是关于79. Word Search的主要内容,如果未能解决你的问题,请参考以下文章

79. Word Search

79. Word Search

LeetCode79. Word Search

79. Word Search

79. Word Search

79. Word Search