Leetcode - Shortest Distance from All Buildings

My code:

import java.util.LinkedList;
import java.util.Queue;

public class Solution {
    private int row = 0;
    private int col = 0;
    private int[][] dir = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
    public int shortestDistance(int[][] grid) {
        if (grid == null || grid.length == 0 || grid[0].length == 0) {
            return -1;
        }
        
        this.row = grid.length;
        this.col = grid[0].length;
        int[][] distance = new int[row][col];
        int[][] reach = new int[row][col];
        int totalBuilding = 0;
        
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == 1) {
                    totalBuilding++;
                    boolean[][] mark = new boolean[row][col];
                    Queue<int[]> q = new LinkedList<int[]>();
                    q.offer(new int[]{i, j});
                    mark[i][j] = true;
                    int level = 1;
                    while (!q.isEmpty()) {
                        int size = q.size();
                        for (int m = 0; m < size; m++) {
                            int[] loc = q.poll();
                            for (int k = 0; k < 4; k++) {
                                int next_x = loc[0] + dir[k][0];
                                int next_y = loc[1] + dir[k][1];
                                if (check(next_x, next_y) && !mark[next_x][next_y] && grid[next_x][next_y] == 0) {
                                    mark[next_x][next_y] = true;
                                    distance[next_x][next_y] += level;
                                    reach[next_x][next_y]++;
                                    q.offer(new int[]{next_x, next_y});
                                }
                            }
                        }
                        level++;
                    }
                }
            }
        }
        
        
        int ret = Integer.MAX_VALUE;
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (grid[i][j] == 0 && reach[i][j] == totalBuilding && distance[i][j] < ret) {
                    ret = distance[i][j];
                }
            }
        }
        
        return ret == Integer.MAX_VALUE ? -1 : ret;
    }
    
    private boolean check(int i, int j) {
        if (i < 0 || i >= row || j < 0 || j >= col) {
            return false;
        }
        else {
            return true;
        }
    }
}

reference:
https://discuss.leetcode.com/topic/31925/java-solution-with-explanation-and-time-complexity-analysis

这道题目让我想起了 multi-end BFS
就是从多个building同时出发,一起遍历。
但是问题在于,如何标志,这个 empty area 被多个Building访问过后的状态?
我没仔细想,直接看了答案。
目前的这个解法,感觉并不是最优的,时间复杂度达到了
O(m * n * m * n)
他解决我说的问题的方法是,
对building 一个个进行BFS,同时维护两个数组,一个累加距离,一个累加到这个点的building 个数。
最后再遍历这个距离数组,如果到这个点的building 个数 = 总building个数,那么这个点可以作为一个最短点,然后我们判断下他的总距离是否最小,如果最小,就更新最小值。

同时,记住, BFS的时候,我们需要一个变量level,这是必须的,用来记录每次距离应该加多少。

时间不知不觉到了10月份了。。好久没刷题了。
加油。未来,就在这最后一个月!

Optimization:
My code:

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class Solution {
    private class Tuple {
        int x;
        int y;
        int distance;
        Tuple(int x, int y, int distance) {
            this.x = x;
            this.y = y;
            this.distance = distance;
        }
    }
    
    private int row = 0;
    private int col = 0;
    private int[][] dir = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
    public int shortestDistance(int[][] grid) {
        if (grid == null || grid.length == 0 || grid[0].length == 0) {
            return -1;
        }
        
        row = grid.length;
        col = grid[0].length;
        int[][] dist = new int[row][col];
        List<Tuple> buildings = new ArrayList<Tuple>();
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (grid[i][j] == 1) {
                    buildings.add(new Tuple(i, j, 0));
                }
                grid[i][j] = -grid[i][j];
            }
        }
        
        for (int i = 0; i < buildings.size(); i++) {
            bfs(buildings.get(i), i, grid, dist);
        }
        
        int ret = Integer.MAX_VALUE;
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (grid[i][j] == buildings.size() && dist[i][j] < ret) {
                    ret = dist[i][j];
                }
            }
        }
        
        return ret == Integer.MAX_VALUE ? -1 : ret;
    }
    
    private void bfs(Tuple root, int k, int[][] grid, int[][] dist) {
        Queue<Tuple> q = new LinkedList<Tuple>();
        q.offer(root);
        while (!q.isEmpty()) {
            Tuple t = q.poll();
            dist[t.x][t.y] += t.distance;
            for (int i = 0; i < 4; i++) {
                int next_x = t.x + dir[i][0];
                int next_y = t.y + dir[i][1];
                if (check(next_x, next_y) && grid[next_x][next_y] == k) {
                    q.offer(new Tuple(next_x, next_y, t.distance + 1));
                    grid[next_x][next_y] = k + 1;
                }
            }
        }
    }
    
    private boolean check(int i, int j) {
        if (i < 0 || i >= row || j < 0 || j >= col) {
            return false;
        }
        return true;
    }
    
    public static void main(String[] args) {
        Solution test = new Solution();
        int[][] input = new int[][]{{1, 0, 2, 0, 1}, {0, 0, 0, 0, 0}, {0, 0, 1, 0, 0}};
        int ret = test.shortestDistance(input);
        System.out.println(ret);
    }
}

reference:
https://discuss.leetcode.com/topic/32391/share-a-java-implement

做完这题,总感觉之前的解法,有太多重复运算。
于是看了更好的解法。
之前的重复在于,如果一个index,他确定不能被一个大楼走到,那么以后对于其他大楼,我们都不需要对他做BFS了,也就是剪枝。
然后现在这个做法,可以很好地剪枝。

Anyway, Good luck, Richardo! -- 10/07/2016

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 162,475评论 4 372
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,744评论 2 307
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 112,101评论 0 254
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,732评论 0 221
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 53,141评论 3 297
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 41,049评论 1 226
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,188评论 2 320
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,965评论 0 213
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,716评论 1 250
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,867评论 2 254
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,341评论 1 265
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,663评论 3 263
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,376评论 3 244
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,200评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,990评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 36,179评论 2 285
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,979评论 2 279

推荐阅读更多精彩内容