public int shortestDistance(int[][] grid) {
        int totalBuild = 0;
        int[][] reach = new int[grid.length][grid[0].length];
        int[][] distance = new int[grid.length][grid[0].length];
        for(int i = 0; i < grid.length; i++) {
            for(int j = 0; j < grid[0].length; j++) {
                if(grid[i][j] == 1) {
                    Queue<Point> queue = new LinkedList<>();
                    queue.offer(new Point(i, j, 0));
                    totalBuild++;
                    boolean[][] visited = new boolean[grid.length][grid[0].length];
                    while (!queue.isEmpty()) {
                        List<Point> neighbors = getNeighbors(queue.poll(), grid, visited, grid.length, grid[0].length);
                        for (Point neigh : neighbors) {
                            visited[neigh.x][neigh.y] = true;
                            reach[neigh.x][neigh.y]++;
                            distance[neigh.x][neigh.y] += neigh.dist;
                            queue.offer(neigh);
                        }
                    }
                }
            }
        }

        int min = Integer.MAX_VALUE;
        for (int i = 0; i < reach.length; i++) {
            for (int j = 0; j < reach[0].length; j++) {
                if (reach[i][j] == totalBuild) {
                    min = Math.min(min, distance[i][j]);
                }
            }
        }

        return min == Integer.MAX_VALUE ? -1 : min;
    }
Date 03/25/2016
@author Tushar Roy

Shortest Distance from All Buildings
https://leetcode.com/problems/shortest-distance-from-all-buildings/
src/com/interview/multiarray/ShortestDistanceFromAllBuildings.java