My Simple Java Manhattan Solution [Accepted]


  • 0
    G

    Hats off to other creative solutions but my simple solution was accepted :

        public int minTotalDistance(int[][] grid) {
            int m = grid.length, n = grid[0].length;
            int[][] dist = new int[m][n];
            for(int i=0;i<m;i++){
                for(int j=0;j<n;j++){
                    if(grid[i][j]==1){
                        updateDist(dist,i,j);
                    }
                }
            }
            
            int res = Integer.MAX_VALUE;
            for(int i=0;i<m;i++){
                for(int j=0;j<n;j++){
                    if(dist[i][j] < res){
                        res = dist[i][j];
                    }
                }
            }
            return res;
        }
        
        public void updateDist(int[][] dist,int x, int y){
            int m = dist.length, n = dist[0].length;
            for(int i=0;i<m;i++){
                for(int j=0;j<n;j++){
                    dist[i][j] += Math.abs(x-i)+Math.abs(y-j);       
                }
            }
        }
    }
    

Log in to reply
 

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