ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

[LeetCode] 286. Walls and Gates

2020-05-02 10:00:50  阅读:355  来源: 互联网

标签:Gates int LeetCode queue Walls rooms INF col row


墙与门。题意是给一个二维矩阵,里面的-1代表墙,0代表门,INF代表一个空的房间。请改写所有的INF,表明每个INF到最近的门的距离。例子

Example: 

Given the 2D grid:

INF  -1  0  INF
INF INF INF  -1
INF  -1 INF  -1
  0  -1 INF INF

After running your function, the 2D grid should be:

  3  -1   0   1
  2   2   1  -1
  1  -1   2  -1
  0  -1   3   4

这一题还是flood fill类的题目,既然是问最短距离,所以我这个题目就用BFS做了。

时间O(mn)

空间O(mn)

Java实现

 1 class Solution {
 2     public void wallsAndGates(int[][] rooms) {
 3         // corner case
 4         if (rooms == null || rooms.length == 0) {
 5             return;
 6         }
 7 
 8         // normal case
 9         Queue<int[]> queue = new LinkedList<>();
10         for (int i = 0; i < rooms.length; i++) {
11             for (int j = 0; j < rooms[0].length; j++) {
12                 if (rooms[i][j] == 0) {
13                     queue.add(new int[] { i, j });
14                 }
15             }
16         }
17         while (!queue.isEmpty()) {
18             int[] cur = queue.poll();
19             int row = cur[0], col = cur[1];
20             if (row > 0 && rooms[row - 1][col] == Integer.MAX_VALUE) {
21                 rooms[row - 1][col] = rooms[row][col] + 1;
22                 queue.offer(new int[] { row - 1, col });
23             }
24             if (row < rooms.length - 1 && rooms[row + 1][col] == Integer.MAX_VALUE) {
25                 rooms[row + 1][col] = rooms[row][col] + 1;
26                 queue.offer(new int[] { row + 1, col });
27             }
28             if (col > 0 && rooms[row][col - 1] == Integer.MAX_VALUE) {
29                 rooms[row][col - 1] = rooms[row][col] + 1;
30                 queue.offer(new int[] { row, col - 1 });
31             }
32             if (col < rooms[0].length - 1 && rooms[row][col + 1] == Integer.MAX_VALUE) {
33                 rooms[row][col + 1] = rooms[row][col] + 1;
34                 queue.offer(new int[] { row, col + 1 });
35             }
36         }
37     }
38 }

 

标签:Gates,int,LeetCode,queue,Walls,rooms,INF,col,row
来源: https://www.cnblogs.com/aaronliu1991/p/12817079.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有