classSolution{publicint[][]updateMatrix(int[][] mat){finalintM= mat.length;// Row size of matfinalintN= mat[0].length;// Column size of matfinalintZERO=0;finalint[][]DIRECTIONS={{1,0},{-1,0},{0,1},{0,-1}};// Directions of up, down, left, right// Queue for the '0's positionsQueue<int[]> q =newLinkedList<>();// Dummy value indicating the cell that haven't been calculatedfinalintDUMMY_VALUE=-1;// Record the address that needed to be updatedfor(int row =0; row <M;++row){for(int col =0; col <N;++col){// Record all the '0' positionif(mat[row][col]==ZERO){
q.add(newint[]{row, col});}else{
mat[row][col]=DUMMY_VALUE;// Fill the cell with dummy value}}}// BFS to update the distancewhile(!q.isEmpty()){int[] curPos = q.poll();// Current positionint rowCurPos = curPos[0];// Row of the current positionint colCurPos = curPos[1];// Column of the current position// Check all the directions of the ZEROfor(int[] direction :DIRECTIONS){int rowSurr = rowCurPos + direction[0];// Row of the surrounding cellint colSurr = colCurPos + direction[1];// Column of the surrounding cell// Check in boundary and it's not the '1' which close to '0'if(isBound(M,N, rowSurr, colSurr)&& mat[rowSurr][colSurr]==DUMMY_VALUE){
q.add(newint[]{rowSurr, colSurr});
mat[rowSurr][colSurr]= mat[rowCurPos][colCurPos]+1;}}}return mat;}// Check if the position is in the boundary of the matrixprivatebooleanisBound(int matM,int matN,int row,int col){return row >=0&& row < matM && col >=0&& col < matN;}}
2023/12/08
再次嘗試,但有點掙扎,沒想到是除了0以外的全部都賦值為-1
classSolution{publicint[][]updateMatrix(int[][] mat){finalintM= mat.length;finalintN= mat[0].length;finalint[][]DIRS={{0,1},{0,-1},{1,0},{-1,0}};// Dummy value indicating the cell that haven't been calculatedfinalintDUMMY_VAL=-1;Queue<int[]> q =newLinkedList<>();for(int m =0; m <M;++m){for(int n =0; n <N;++n){if(mat[m][n]==0){
q.add(newint[]{m, n});}else{
mat[m][n]=DUMMY_VAL;}}}while(!q.isEmpty()){int[] cell = q.poll();// Check four directionsfor(int[] dir :DIRS){int row = dir[0]+ cell[0];int col = dir[1]+ cell[1];if(inBound(M,N, row, col)&& mat[row][col]==DUMMY_VAL){
q.add(newint[]{row, col});
mat[row][col]= mat[cell[0]][cell[1]]+1;}}}return mat;}privatebooleaninBound(int m,int n,int row,int col){return row >=0&& row < m && col >=0&& col < n;}}