LeetCode Walls and Gates

來源:互聯網
上載者:User

標籤:

原題連結在這裡:https://leetcode.com/problems/walls-and-gates/

題目:

You are given a m x n 2D grid initialized with these three possible values.

  1. -1 - A wall or an obstacle.
  2. 0 - A gate.
  3. INF - Infinity means an empty room. We use the value 231 - 1 = 2147483647 to represent INF as you may assume that the distance to a gate is less than2147483647.

Fill each empty room with the distance to its nearest gate. If it is impossible to reach a gate, it should be filled with INF.

For example, given the 2D grid:

INF  -1  0  INFINF INF INF  -1INF  -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

題解:

BFS, 先把所有gate加到que中。對於每一個從que中poll出來的gate,看四個方向是否有room, 若有,把room的值改正gate + 1, 在放回到que中.

Time Complexity: O(m*n). m = rooms.length, n = rooms[0].length. 每個點沒有掃描超過兩遍. Space: O(m*n). 

AC Java:

 1 public class Solution { 2     public void wallsAndGates(int[][] rooms) { 3         if(rooms == null || rooms.length == 0 || rooms[0].length == 0){ 4             return; 5         } 6         int [][] fourDire = {{0,1},{0,-1},{1,0},{-1,0}}; 7         LinkedList<int []> que = new LinkedList<int []>(); 8          9         for(int i = 0; i<rooms.length; i++){10             for(int j = 0; j<rooms[0].length; j++){11                 if(rooms[i][j] == 0){12                     que.add(new int[]{i,j});13                 }14             }15         }16         17         while(!que.isEmpty()){18             int [] gate = que.poll();19             int x = gate[0];20             int y = gate[1];21             for(int k = 0; k<4; k++){22                 int newX = x + fourDire[k][0];23                 int newY = y + fourDire[k][1];24                 if(newX>=0 && newX<rooms.length && newY>=0 && newY<rooms[0].length){25                     if(rooms[newX][newY] == Integer.MAX_VALUE){26                         rooms[newX][newY] = rooms[x][y] + 1;27                         que.add(new int[]{newX, newY});28                     }29                 }30             }31         }32     }33 }

 

LeetCode Walls and Gates

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.