using DFS, but overflow! Help me out!!!


  • 0
    T
    public class Solution {
        public int[][] updateMatrix(int[][] matrix) {
             if(matrix==null || matrix.length<1) return null;
             
             int[][] res=new int[matrix.length][matrix[0].length];
             
             for(int i=0;i<matrix.length;i++){
                 for(int j=0;j<matrix[0].length;j++){
                     dfs(matrix,res,i,j);
                 }
             }
             return res;
        }
        
        public int dfs(int[][] matrix,int[][] res,int row,int col){
            if(matrix[row][col]==0) return 0;
            if(res[row][col]!=0) return res[row][col];
            
            int[][] dirs=new int[][]{{-1,0},{1,0},{0,1},{0,-1}};
            int len=Integer.MAX_VALUE;
            for(int[] dir:dirs){
                int i=dir[0]+row;
                int j=dir[1]+col;
                if(i>=0&&i<res.length&&j>=0&&j<res[0].length){
                    len=Math.min(len,1+dfs(matrix,res,i,j));
                }
            }
            
            res[row][col]=len;
            return len;
        }
    }
             
    
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.