zoukankan      html  css  js  c++  java
  • 286. 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 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, 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

    广度优先, 如果有多个起点谁先抢到某个点, 就标记上到该起点的距离, 所以距离是较小的那一个值
    #include <iostream>
    #include <vector>
    #include <queue>
    using namespace std;
    
    class Solution {
    	
    	private:
    		const int dir[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};
    		int m, n;
    		
    		const int GATE = 0;
    		const int EMPTY = INT_MAX;
    		const int WALL = -1;
    	
    	public:
    		
    		void wallsAndGates(vector<vector<int> >& rooms) {
    			
    			m = rooms.size();
    			if(m == 0)	return ;
    			n = rooms.size();
    			
    			bfs(rooms);
    			return ;
    		}
    	
    	private:
    		
    		void bfs(vector<vector<int> >& rooms) {
    			
    			queue<pair<pair<int, int>, int> > q;
    			for(int i = 0; i < m; ++ i) {
    				for(int j = 0; j < n; ++ j) {
    					if(rooms[i][j] == GATE) {
    						q.push(make_pair(make_pair(i, j), 0));
    					}
    				}
    			}
    			vector<vector<bool> > visited(m, vector<bool>(n, false));
    			
    			while(!q.empty()) {
    				
    				int curx = q.front().first.first;
    				int cury = q.front().first.second;
    				int step = q.front().second;
    				q.pop();
    				
    				rooms[curx][cury] = step;
    				for(int i = 0; i < 4; ++ i) {
    					int newX = curx + dir[i][0];
    					int newY = cury + dir[i][1];
    					if(inArea(newX, newY) && !visited[newX][newY] && rooms[newX][newY] == EMPTY) {
    						
    						visited[newX][newY] = true;
    						rooms[newX][newY] = step + 1;
    						q.push(make_pair(make_pair(newX, newY), step + 1));
    					}
    				}
    			}
    		}
    		
    		bool inArea(int x, int y) {
    			return x >= 0 && x < m && y >= 0 && y < n;
    		}
    };
    
    
    /*
    INF  -1  0  INF
    INF INF INF  -1
    INF  -1 INF  -1
      0  -1 INF INF
      
      3  -1   0   1
      2   2   1  -1
      1  -1   2  -1
      0  -1   3   4
    */
    

      

  • 相关阅读:
    用ps 查看线程状态
    机器学习资料收集
    [转]漫谈数据中心CLOS网络架构
    MBR中“起始磁头/扇区/柱面“同"逻辑区块地址(LBA)"的区别
    [转]硬盘分区表知识——详解硬盘MBR
    [转]什么是总线?什么是前端总线?
    语言的编译-汇编-链接
    计算机进行小数运算会出错

    计算机底层是如何访问显卡的?
  • 原文地址:https://www.cnblogs.com/mjn1/p/11158120.html
Copyright © 2011-2022 走看看