首页 > 其他 > 详细

【剑指offer】【搜索和回溯】12. 矩阵中的路径

时间:2020-05-04 14:27:58      阅读:63      评论:0      收藏:0      [点我收藏+]

题目链接:https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof/

dfs

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;
    }
    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;
        int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
        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[a].size()){
                if(dfs(board, word, u + 1, a, b)) return true;
            }
        }
        board[x][y] = t;
        return false;
    }
};

【剑指offer】【搜索和回溯】12. 矩阵中的路径

原文:https://www.cnblogs.com/Trevo/p/12728697.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!