登录
  • #eecs

求助‌‌‍‍‌‍‍‌‍‌‍‍‌‍‍‍‍‍‍‌‍‍‍‌‌‍‍‌‍‌‍‌一道leetcode题 题号--542

glennW97
460
5
求助大佬,542 01矩阵这道题我的解法错哪里了?

我的解法如下:

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++) {

if (mat[j] == 1) {

visited = new boolean[m][n];

distance = 0;

dfs(i, j , mat, ans, m, n, 0, visited);

}

}

}

return ans;

}

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[j] == true) {

return;

}

if (mat[j] == 0) {

visited[j] = true;

if (distance == 0) {

distance = dist;

}

return;

}

visited[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[j] = distance;

}

}

出错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]]

疑惑点: 我的distance 是全局变量 每次dfs前都刷新为1 按理说会根据dfs深度递增 一次dfs为1 两次dfs为2
5条回复
热度排序

发表回复