码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode-----79. 单词搜索

时间:2020-07-14 21:55:49      阅读:84      评论:0      收藏:0      [点我收藏+]

标签:com   false   ++   arch   problems   --   代码   leetcode   class   

代码

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[i].size(); ++j) {
                if (dfs(board, word, 0, i, j)) return true;
            }
        }
        return false;
    }

    int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
    bool dfs(vector<vector<char>>& board, string& word, int u, int x, int y) {
        if (board[x][y] != word[u]) return false;
        if (u == word.size() - 1) return true;

        char t = board[x][y];
        board[x][y] = ‘.‘;
        for (int i = 0; i < 4; ++i) {
            int a = x + dx[i], b = y + dy[i];
            if (a < 0 || a >= board.size() || b < 0 || b >= board[0].size() || board[a][b] == ‘.‘) continue;
            if (dfs(board, word, u + 1, a, b)) return true;
        }
        board[x][y] = t;
        return false;
    }
};

leetcode-----79. 单词搜索

标签:com   false   ++   arch   problems   --   代码   leetcode   class   

原文地址:https://www.cnblogs.com/clown9804/p/13301818.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!