查看: 723| 回复: 0
跳转到指定楼层
上一主题 下一主题
收起左侧

[转CS-自学] 求助一道leetcode题 题号--542

全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
求助大佬,542 01矩阵这道题我的解法错哪里了?. 1point 3acres
. Χ
我的解法如下:
class Solution {
    int distance = 0;.--
    public int[][] updateMatrix(int[][] mat) {
        //用distance记录最先找到0的递归次数 然后在递归开始的位置上放上这个distance  
        int m = mat.length;
        int n = mat[0].length;
        int[][] ans = new int[m][n];.
        boolean[][] visited;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {  . 1point 3 acres
                if (mat[i][j] == 1) {
                    visited = new boolean[m][n];
                    distance = 0;.1point3acres
                    dfs(i, j , mat, ans, m, n, 0, visited);
                }
            }
        }
. ----        return ans;
    }. 1point 3acres
    public void dfs(int i, int j, int[][] mat, int[][] ans, int m, int n, int dist, boolean[][] visited) {
        if (i < 0 || i >= m || j < 0 || j >= n || visited[i][j] == true) {
            return;. .и
        }
        if (mat[i][j] == 0) {
            visited[i][j] = true;
            if (distance == 0) {. From 1point 3acres bbs
                distance = dist;               
            }
            return;
        }
        visited[i][j] = true;
        dfs(i-1, j, mat, ans, m, n,dist+1, visited);
        dfs(i, j-1, mat, ans, m, n,dist+1, visited);
        dfs(i+1, j, mat, ans, m, n,dist+1,visited);
        dfs(i, j+1, mat, ans, m, n,dist+1,visited);
        ans[i][j] = distance;
    }
}.1point3acres
出错case: [[0,0,0],[0,1,0],[1,1,1]]
输出结果 [[0,0,0],[0,1,0],[1,1,1]] 期望结果[[0,0,0],[0,1,0],[1,2,1]]  . 1point3acres
疑惑点: 我的distance 是全局变量 每次dfs前都刷新为1  按理说会根据dfs深度递增 一次dfs为1 两次dfs为2




上一篇:模拟ic硕士就业
下一篇:求助一道leetcode题 题号--542
您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表