zoukankan      html  css  js  c++  java
  • [LintCode] 663. Walls and Gates

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

    -1 - A wall or an obstacle.
    0 - A gate.
    INF - Infinity means an empty room. We use the value 2^31 - 1 = 2147483647 to represent INF as you may assume that the distance to a gate is less than 2147483647.
    Fill each empty room with the distance to its nearest gate. If it is impossible to reach a Gate, that room should remain filled with INF

    Example

    Example1

    Input:
    [[2147483647,-1,0,2147483647],[2147483647,2147483647,2147483647,-1],[2147483647,-1,2147483647,-1],[0,-1,2147483647,2147483647]]
    Output:
    [[3,-1,0,1],[2,2,1,-1],[1,-1,2,-1],[0,-1,3,4]]
    
    Explanation:
    the 2D grid is:
    INF  -1  0  INF
    INF INF INF  -1
    INF  -1 INF  -1
      0  -1 INF INF
    the answer is:
      3  -1   0   1
      2   2   1  -1
      1  -1   2  -1
      0  -1   3   4
    

    Example2

    Input:
    [[0,-1],[2147483647,2147483647]]
    Output:
    [[0,-1],[1,2]]


    public class Solution {
        /**
         * @param rooms: m x n 2D grid
         * @return: nothing
         */
        public void wallsAndGates(int[][] rooms) {
            // write your code here
            Queue<Cell> queue = new LinkedList<>();
            int row = rooms.length;
            int col = rooms[0].length;
            for (int i = 0; i < row; i++) {
                for (int j = 0; j < col; j++) {
                    if (rooms[i][j] == 0) {
                        // x correspond to i => row, y correspond to j => col
                        // start from the smallest point
                        queue.offer(new Cell(i, j, rooms[i][j]));
                    }
                }
            }
            
            int[][] directions = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
            while (!queue.isEmpty()) {
                Cell cur = queue.poll();
                for (int[] dir: directions) {
                    int newX = cur.x + dir[0];
                    int newY = cur.y + dir[1];
                    if (newX >= 0 && newX < row && newY >= 0 && newY < col && rooms[newX][newY] == Integer.MAX_VALUE) {
                        rooms[newX][newY] = cur.val + 1;
                        queue.offer(new Cell(newX, newY, rooms[newX][newY]));
                    }
                }
            }
        }
    }
    
    class Cell {
        int x;
        int y; 
        int val;
        public Cell(int x, int y, int val) {
            this.x = x;
            this.y = y;
            this.val = val;
        }
    }
  • 相关阅读:
    性能测试系列七 工具选择
    Selenium Web自动化面试题总结(下篇)
    性能测试系列六 评估压测量
    hexo 安装
    光纤收发器组网方式
    频谱仪
    交换机网管telent
    区块链共识机制
    SDH、MSTP、OTN和PTN
    ACL知识
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12521808.html
Copyright © 2011-2022 走看看