zoukankan      html  css  js  c++  java
  • Walls and Gates -- LeetCode

    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 than 2147483647.

    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  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

    思路:BSF。

     1 class Solution {
     2 public:
     3     void wallsAndGates(vector<vector<int>>& rooms) {
     4         const int inf = INT_MAX;
     5         queue<pair<int, int> > q;
     6         int height = rooms.size();
     7         int width = height > 0 ? rooms[0].size() : 0;
     8         for (int i = 0; i < height; i++)
     9             for (int j = 0; j < width; j++)
    10                 if (rooms[i][j] == 0) q.push(make_pair(i, j));
    11         int rowChange[] = {0, -1, 0, 1};
    12         int colChange[] = {1, 0, -1, 0};
    13         while (!q.empty()) {
    14             pair<int, int> cur = q.front();
    15             q.pop();
    16             int row = get<0>(cur), col = get<1>(cur);
    17             for (int i = 0; i < 4; i++) {
    18                 int nextRow = row + rowChange[i];
    19                 int nextCol = col + colChange[i];
    20                 if (nextRow > -1 && nextRow < height &&
    21                     nextCol > -1 && nextCol < width && rooms[nextRow][nextCol] == inf) {
    22                         rooms[nextRow][nextCol] = rooms[row][col] + 1;
    23                         q.push(make_pair(nextRow, nextCol));
    24                     }
    25             }
    26         }
    27     }
    28 };
  • 相关阅读:
    516. Longest Palindromic Subsequence最长的不连续回文串的长度
    java之spring之整合ssh-2
    java之spring之整合ssh
    java之spring之spring整合hibernate
    微服务之初了解(一)
    java之spring之scope和autowiring
    java之spring之依赖注入
    java之spring之对象的创建
    java之spring之配置讲解
    asp.net core 系列之静态文件
  • 原文地址:https://www.cnblogs.com/fenshen371/p/5798462.html
Copyright © 2011-2022 走看看