题解1:广度遍历
是从0出发 然后一步能到的设置为1遍历矩阵设为遍历过 入队 再看一步能到的设置为2
题解2:动态规划
改不对 bug是因为没有设置已经遍历过的元素的标识 导致会回找 不断循环 死循环爆栈
算了
public static void main(String[] args) { // TODO Auto-generated method stub //bug是因为没有设置已经遍历过的元素的标识 导致会回找 不断循环 死循环爆栈 // int[][] mat= {{1,0,0,0,1,1,1,1,0,1}, // {1,1,1,1,1,1,1,0,1,0},{1,1,1,1,0,1,0,0,1,1}}; // int[][] mat= {{1,0,1,1,0,0,1,0,0,1},{0,1,1,0,1,0,1,0,1,1}, // {0,0,1,0,1,0,0,1,0,0},{1,0,1,0,1,1,1,1,1,1}, // {0,1,0,1,1,0,0,0,0,1},{0,0,1,0,1,1,1,0,1,0}, // {0,1,0,1,0,1,0,0,1,1},{1,0,0,0,1,1,1,1,0,1}, // {1,1,1,1,1,1,1,0,1,0},{1,1,1,1,0,1,0,0,1,1}}; int[][] mat={{1,1,1},{1,1,0},{1,1,1}}; int[][]res =Leetcode542.updateMatrix(mat); for(int i=0;i<mat.length;i++) { for(int j=0;j<mat[0].length;j++) { System.out.println(res[i][j]); } } } public static int[][] updateMatrix(int[][] mat) { int row=mat.length,line=mat[0].length; int[][]res=new int[row][line]; for(int i=0;i<row;i++) { for(int j=0;j<line;j++) { if(mat[i][j]==0) { res[i][j]=0; } else{ res[i][j]=recent_1(mat,i,j); } } } return res; } public static int recent_1(int[][] mat,int i,int j) { int row=mat.length,line=mat[0].length; int[][]flag=new int[row][line]; int[] dx= {0,0,-1,1},dy= {1,-1,0,0}; int res=Integer.MAX_VALUE; Queue<int[]> queue =new LinkedList<int[]>(); flag[i][j]=1; for(int k=0;k<4;k++) { // int step=1; if(i+dx[k]>-1 && i+dx[k]<row && j+dy[k]>-1 && j+dy[k]<line ) { flag[i+dx[k]][j+dy[k]]=1; if(mat[i+dx[k]][j+dy[k]]==0) { return 1; } else if(mat[i+dx[k]][j+dy[k]]==1 && flag[i+dx[k]][j+dy[k]]==0) { queue.offer(new int[]{i+dx[k],j+dy[k]}); // step=step+1; } } } while(!queue.isEmpty()) { int[]para=queue.poll(); res=Math.min(res, 1+recent_1(mat,para[0],para[1])); } queue.clear(); return res; }
标签:542,01,mat,int,题解,矩阵,力扣,遍历,设置 From: https://www.cnblogs.com/ayuanjiejie/p/17198698.html