【LeetCode 803】Bricks Falling When Hit

题目描述

We have a grid of 1s and 0s; the 1s in a cell represent bricks. A brick will not drop if and only if it is directly connected to the top of the grid, or at least one of its (4-way) adjacent bricks will not drop.

We will do some erasures sequentially. Each time we want to do the erasure at the location (i, j), the brick (if it exists) on that location will disappear, and then some other bricks may drop because of that erasure.

Return an array representing the number of bricks that will drop after each erasure in sequence.

Example 1:

Input: 
grid = [[1,0,0,0],[1,1,1,0]]
hits = [[1,0]]
Output: [2]
Explanation: 
If we erase the brick at (1, 0), the brick at (1, 1) and (1, 2) will drop. So we should return 2.

Example 2:

Input: 
grid = [[1,0,0,0],[1,1,0,0]]
hits = [[1,1],[1,0]]
Output: [0,0]
Explanation: 
When we erase the brick at (1, 0), the brick at (1, 1) has already disappeared due to the last move. So each erasure will cause no bricks dropping.  Note that the erased brick (1, 0) will not be counted as a dropped brick.

Note:

The number of rows and columns in the grid will be in the range [1, 200].
The number of erasures will not exceed the area of the grid.
It is guaranteed that each erasure will be different from any other erasure, and located inside the grid.
An erasure may refer to a location with no brick - if it does, no bricks drop.

思路

找连通块,如果这个连通块能连接到顶层,不掉。

代码

class Solution {
public:
    vector<int> hitBricks(vector<vector<int>>& grid, vector<vector<int>>& hits) {
        dirs = {1, 0, -1, 0, 1};
        m_ = grid.size();
        n_ = grid[0].size();
        g_.swap(grid);
        seq_ = 1;
        
        vector<int> ans;
        for (int i=0; i<hits.size(); ++i) {
            ans.push_back(hit(hits[i][0], hits[i][1]));
        }
        return ans;
    }
    
private:
    vector<vector<int>> g_;
    vector<int> dirs;
    int seq_;
    int m_;
    int n_;
    
    int hit(int x, int y) {
        if (x < 0 || x >= m_ || y < 0 || y >= n_) return 0;
        g_[x][y] = 0;
        int ans = 0;
        for (int i=0; i<4; ++i) {
            ++seq_;
            int count = 0;
            if (!fall(x+dirs[i], y+dirs[i+1], false, count)) continue;
            ++seq_;
            ans += count;
            fall(x+dirs[i], y+dirs[i+1], true, count);
        }
        return ans;
    }
    
    bool fall(int x, int y, bool clear, int& count) {
        if (x < 0 || x >= m_ || y < 0 || y >= n_) return true;
        if (g_[x][y] == seq_ || g_[x][y] == 0) return true;
        if (x == 0) return false;
        
        g_[x][y] = (clear ? 0 : seq_);
        ++count;
        for (int i=0; i<4; ++i) {
            if (!fall(x+dirs[i], y+dirs[i+1], clear, count)) return false;
        }
        return true;
    }
};

==========================================
还是没太整明白。。。。。.。。。。。。。。。。。

发布了323 篇原创文章 · 获赞 10 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/iCode_girl/article/details/104910588