Algorithm Practice
  • Introduction
  • Lintcode
    • Expression Evaluation
  • Leetcode
    • Math
      • 223 Rectangle Area
      • 750 Number Of Corner Rectangles
    • Tree
      • 94 Binary Tree Inorder Traversal
      • 100 Same Tree
      • 114 Flatten Binary Tree to Linked List
      • 116 Populating Next Right Pointers in Each Node
      • 117 Populating Next Right Pointers in Each Node II
      • 124 Binary Tree Maximum Path Sum
      • 144 Binary Tree Preorder Traversal
      • 145 Binary Tree Postorder Traversal
      • 366 Find Leaves of Binary Tree
      • 257 Binary Tree Paths
      • 235 Lowest Common Ancestor of a Binary Search Tree
      • 236 Lowest Common Ancestor of a Binary Tree
      • 671 Second Minimum Node In a Binary Tree
      • 662 Maximum Width of Binary Tree
      • 101 Symmetric Tree
      • 102 Binary Tree Level Order Traversal
      • 103 Binary Tree Zigzag Level Order Traversal
      • 104 Maximum Depth of Binary Tree
      • 107 Binary Tree Level Order Traversal II
      • 108 Convert Sorted Array to Binary Search Tree
      • 110 Balanced Binary Tree
      • 111 Minimum Depth of Binary Tree
      • 112 Path Sum
      • 113 Path Sum II
      • 623 Add One Row to Tree
      • 222 Count Complete Tree Nodes
      • 450 Delete Node in a BST
      • 156 Binary Tree Upside Down
      • 536 Construct Binary Tree from String
      • 543 Diameter of Binary Tree
      • 545 Boundary of Binary Tree
      • 105 Construct Binary Tree from Preorder and Inorder Traversal
      • 106 Construct Binary Tree from Inorder and Postorder Traversal
      • 606 Construct String from Binary Tree
      • 655 Print Binary Tree
      • 742 Closest Leaf in a Binary Tree
      • 783 Minimum Distance Between BST Nodes
    • Graph
      • 133 Clone Graph
      • 200 Number of Islands
      • 261 Graph Valid Tree
      • 301 Remove Invalid Parentheses
      • 310 Minimum Height Trees
      • 329 Longest Increasing Path in a Matrix
      • 323 Number of Connected Components in an Undirected Graph
      • 332 Reconstruct Itinerary
      • 337 House Robber III
      • 339 Nested List Weight Sum
      • 364 Nested List Weight Sum II
      • 399 Evaluate Division
      • 417 Pacific Atlantic Water Flow
      • 488 Zuma Game
      • 490 The Maze
      • 494 Target Sum
      • 499 The Maze III
      • 505 The Maze II
      • 529 Minesweeper
      • 531 Lonely Pixel I
      • 533 Lonely Pixel II
      • 542 01 Matrix
      • 547 Friend Circles
      • 685 Redundant Connection II
      • 690 Employee Importance
      • 694 Number of Distinct Islands
      • 695 Max Area of Island
      • 711 Number of Distinct Islands II
      • 721 Accounts Merge
      • 733 Flood Fill
      • 737 Sentence Similarity II
    • Two Pointers
      • 3 Longest Substring Without Repeating Characters
      • 11 Container With Most Water
      • 15 3Sum
      • 16 3Sum Closest
      • 18 4Sum
      • 26 Remove Duplicates from Sorted Array
      • 27 Remove Element
      • 30 Substring with Concatenation of All Words
      • 42 Trapping Rain Water
      • 76 Minimum Window Substring
      • 80 Remove Duplicates from Sorted Array II
      • 88 Merge Sorted Array
      • 125 Valid Palindrome
      • 159 Longest Substring with At Most Two Distinct Characters
      • 167 Two Sum II - Input array is sorted
      • 202 Happy Number
      • 209 Minimum Size Subarray Sum
      • 259 3Sum Smaller
      • 283 Move Zeroes
      • 340 Longest Substring with At Most K Distinct Characters
      • 344 Reverse String
      • 345 Reverse Vowels of a String
      • 349 Intersection of Two Arrays
      • 350 Intersection of Two Arrays II
      • 360 Sort Transformed Array
      • 395 Longest Substring with At Least K Repeating Characters
      • 424 Longest Repeating Character Replacement
      • 438 Find All Anagrams in a String
      • 487 Max Consecutive Ones II
      • 524 Longest Word in Dictionary through Deleting
      • 532 K-diff Pairs in an Array
      • 567 Permutation in String
      • 611 Valid Triangle Number
      • 632 Smallest Range
      • 713 Subarray Product Less Than K
      • 723 Candy Crush
      • 763 Partition Labels
    • Linked List
      • 2 Add Two Numbers
      • 21 Merge Two Sorted Lists
      • 23 Merge k Sorted Lists
      • 61 Rotate List
      • 82 Remove Duplicates from Sorted List II
      • 83 Remove Duplicates from Sorted List
      • 86 Partition List
      • 92 Reverse Linked List II
      • 109 Convert Sorted List to Binary Search Tree
      • 141 Linked List Cycle
      • 142 Linked List Cycle II
      • 203 Remove Linked List Elements
      • 206 Reverse Linked List
      • 234 Palindrome Linked List
      • 237 Delete Node in a Linked List
      • 328 Odd Even Linked List
      • 369 Plus One Linked List
      • 379 Design Phone Directory
      • 445 Add Two Numbers II
      • 725 Split Linked List in Parts
      • 817 Linked List Components
      • 148 Sort List
    • Topological Sort
      • 207 Course Schedule
      • 210 Course Schedule II
      • 269 Alien Dictionary
      • 444 Sequence Reconstruction
      • 802 Find Eventual Safe States
    • Hash Table
      • 599 Minimum Index Sum of Two Lists
      • 697 Degree of an Array
      • 734 Sentence Similarity
      • 749 Shortest Completing Word
      • 760 Find Anagram Mappings
    • Trie
      • 208 Implement Trie (Prefix Tree)
      • 211 Add and Search Word - Data structure design
      • 336 Palindrome Pairs
      • 421 Maximum XOR of Two Numbers in an Array
      • 472 Concatenated Words
      • 642 Design Search Autocomplete System
      • 648 Replace Words
      • 676 Implement Magic Dictionary
      • 677 Map Sum Pairs
      • 692 Top K Frequent Words
      • 720 Longest Word in Dictionary
      • 745 Prefix and Suffix Search
    • Sort
      • 49 Group Anagrams
      • 75 Sort Colors
      • 164 Maximum Gap
      • 179 Largest Number
      • 274 H-Index
      • 280 Wiggle Sort
      • 296 Best Meeting Point
      • 315 Count of Smaller Numbers After Self
      • 324 Wiggle Sort II
      • 327 Count of Range Sum
      • 406 Queue Reconstruction by Height
      • 462 Minimum Moves to Equal Array Elements II
      • 493 Reverse Pairs
    • Binary Search
      • 4 Median of Two Sorted Arrays
      • 29 Divide Two Integers
      • 33 Search in Rotated Sorted Array
      • 34 Search for a Range
      • 35 Search Insert Position
      • 50 Pow(x, n)
      • 69 Sqrt(x)
      • 74 Search a 2D Matrix
      • 81 Search in Rotated Sorted Array II
      • 153 Find Minimum in Rotated Sorted Array
      • 154 Find Minimum in Rotated Sorted Array II
      • 162 Find Peak Element
      • 240 Search a 2D Matrix II
      • 275 H-Index II
      • 278 First Bad Version
      • 287 Find the Duplicate Number
      • 302 Smallest Rectangle Enclosing Black Pixels
      • 367 Valid Perfect Square
      • 374 Guess Number Higher or Lower
      • 410 Split Array Largest Sum
      • 436 Find Right Interval
      • 441 Arranging Coins
      • 475 Heaters
      • 483 Smallest Good Base
      • 540 Single Element in a Sorted Array
      • 633 Sum of Square Numbers
      • 644 Maximum Average Subarray II
      • 658 Find K Closest Elements
      • 719 Find K-th Smallest Pair Distance
      • 744 Find Smallest Letter Greater Than Target
      • 774 Minimize Max Distance to Gas Station
      • 778 Swim in Rising Water
    • Heap
      • 215 Kth Largest Element in an Array
      • 239 Sliding Window Maximum
      • 253 Meeting Rooms II
      • 264 Ugly Number II
      • 295 Find Median from Data Stream
      • 313 Super Ugly Number
      • 347 Top K Frequent Elements
      • 358 Rearrange String k Distance Apart
      • 373 Find K Pairs with Smallest Sums
      • 378 Kth Smallest Element in a Sorted Matrix
      • 407 Trapping Rain Water II
      • 451 Sort Characters By Frequency
      • 480 Sliding Window Median
      • 502 IPO
      • 659 Split Array into Consecutive Subsequences
      • 668 Kth Smallest Number in Multiplication Table
      • 692 Top K Frequent Words
      • 759 Employee Free Time
      • 767 Reorganize String
      • 778 Swim in Rising Water
      • 973. K Closest Points to Origin
    • Breadth First Search
      • 126 Word Ladder II
      • 127 Word Ladder
      • 130 Surrounded Regions
      • 279 Perfect Squares
      • 286 Walls and Gates
      • 317 Shortest Distance from All Buildings
      • 397 Integer Replacement
      • 407 Trapping Rain Water II
      • 433 Minimum Genetic Mutation
      • 675 Cut Off Trees for Golf Event
      • 743 Network Delay Time
      • 752 Open the Lock
      • 773 Sliding Puzzle
      • 787 Cheapest Flights Within K Stops
    • Stack
      • 20 Valid Parentheses
      • 71 Simplify Path
      • 84 Largest Rectangle in Histogram
      • 85 Maximal Rectangle
      • 150 Evaluate Reverse Polish Notation
      • 155 Min Stack
      • 173 Binary Search Tree Iterator
      • 224 Basic Calculator
      • 225 Implement Stack using Queues
      • 232 Implement Queue using Stacks
      • 255 Verify Preorder Sequence in Binary Search Tree
      • 316 Remove Duplicate Letters
      • 331 Verify Preorder Serialization of a Binary Tree
      • 341 Flatten Nested List Iterator
      • 385 Mini Parser
      • 394 Decode String
      • 402 Remove K Digits
      • 439 Ternary Expression Parser
      • 456 132 Pattern
      • 496 Next Greater Element I
      • 503 Next Greater Element II
      • 581 Shortest Unsorted Continuous Subarray
      • 591 Tag Validator
      • 636 Exclusive Time of Functions
      • 654 Maximum Binary Tree
      • 682 Baseball Game
      • 726 Number of Atoms
      • 735 Asteroid Collision
      • 739 Daily Temperatures
      • 770 Basic Calculator IV
      • 772 Basic Calculator III
    • Backtracking
      • 10 Regular Expression Matching
      • 17 Letter Combinations of a Phone Number
      • 22 Generate Parentheses
      • 37 Sudoku Solver
      • 39 Combination Sum
      • 40 Combination Sum II
      • 44 Wildcard Matching
      • 46 Permutations
      • 47 Permutations II
      • 51 N-Queens
      • 52 N-Queens II
      • 60 Permutation Sequence
      • 77 Combinations
      • 78 Subsets
      • 79 Word Search
      • 89 Gray Code
      • 90 Subsets II
      • 93 Restore IP Addresses
      • 131 Palindrome Partitioning
      • 212 Word Search II
      • 216 Combination Sum III
      • 254 Factor Combinations
      • 267 Palindrome Permutation II
      • 291 Word Pattern II
      • 320 Generalized Abbreviation
      • 351 Android Unlock Patterns
      • 357 Count Numbers with Unique Digits
      • 401 Binary Watch
      • 411 Minimum Unique Word Abbreviation
      • 425 Word Squares
      • 473 Matchsticks to Square
      • 491 Increasing Subsequences
      • 526 Beautiful Arrangement
      • 679 24 Game
      • 691 Stickers to Spell Word
      • 797 All Paths From Source to Target
    • Dynamic Programming
      • LIS
        • 300 Longest Increasing Subsequence
        • 334 Increasing Triplet Subsequence
        • 354 Russian Doll Envelopes
        • 376 Wiggle Subsequence
        • 368 Largest Divisible Subset
        • 646 Maximum Length of Pair Chain
        • 673 Number of Longest Increasing Subsequence
      • Longest Common Subsequence
        • 5 Longest Palindromic Substring
        • 72 Edit Distance
        • 115 Distinct Subsequences
        • 392 Is Subsequence
        • 516 Longest Palindromic Subsequence
        • 583 Delete Operation for Two Strings
        • 647 Palindromic Substrings
        • 712 Minimum ASCII Delete Sum for Two Strings
      • Interval DP
        • 132 Palindrome Partitioning II
        • 312 Burst Balloons
        • 375 Guess Number Higher or Lower II
        • 471 Encode String with Shortest Length
        • 486 Predict the Winner
        • 516 Longest Palindromic Subsequence
        • 546 Remove Boxes
      • Knapsack Problem
        • 322 Coin Change
        • 377 Combination Sum IV
        • 416 Partition Equal Subset Sum
        • 474 Ones and Zeroes
        • 494 Target Sum
        • 518 Coin Change 2
      • 10 Regular Expression Matching
      • 32 Longest Valid Parentheses
      • 44 Wildcard Matching
      • 53 Maximum Subarray
      • 62 Unique Paths
      • 63 Unique Paths II
      • 64 Minimum Path Sum
      • 70 Climbing Stairs
      • 85 Maximal Rectangle
      • 87 Scramble String
      • 91 Decode Ways
      • 95 Unique Binary Search Trees II
      • 96 Unique Binary Search Trees
      • 97 Interleaving String
      • 120 Triangle
      • 121 Best Time to Buy and Sell Stock
      • 122 Best Time to Buy and Sell Stock II
      • 123 Best Time to Buy and Sell Stock III
      • 139 Word Break
      • 140 Word Break II
      • 152 Maximum Product Subarray
      • 174 Dungeon Game
      • 188 Best Time to Buy and Sell Stock IV
      • 198 House Robber
      • 213 House Robber II
      • 221 Maximal Square
      • 238 Product of Array Except Self
      • 256 Paint House
      • 264 Ugly Number II
      • 265 Paint House II
      • 276 Paint Fence
      • 279 Perfect Squares
      • 303 Range Sum Query - Immutable
      • 304 Range Sum Query 2D - Immutable
      • 309 Best Time to Buy and Sell Stock with Cooldown
      • 321 Create Maximum Number
      • 338 Counting Bits
      • 343 Integer Break
      • 361 Bomb Enemy
      • 363 Max Sum of Rectangle No Larger Than K
      • 368 Largest Divisible Subset
      • 403 Frog Jump
      • 410 Split Array Largest Sum
      • 413 Arithmetic Slices
      • 418 Sentence Screen Fitting
      • 446 Arithmetic Slices II - Subsequence
      • 464 Can I Win
      • 466 Count The Repetitions
      • 467 Unique Substrings in Wraparound String
      • 471 Encode String with Shortest Length
      • 514 Freedom Trail
      • 517 Super Washing Machines
      • 523 Continuous Subarray Sum
      • 552 Student Attendance Record II
      • 562 Longest Line of Consecutive One in Matrix
      • 568 Maximum Vacation Days
      • 576 Out of Boundary Paths
      • 600 Non-negative Integers without Consecutive Ones
      • 629 K Inverse Pairs Array
      • 638 Shopping Offers
      • 639 Decode Ways II
      • 650 2 Keys Keyboard
      • 651 4 Keys Keyboard
      • 656 Coin Path
      • 688 Knight Probability in Chessboard
      • 689 Maximum Sum of 3 Non-Overlapping Subarrays
      • 691 Stickers to Spell Word
      • 698 Partition to K Equal Sum Subsets
      • 714 Best Time to Buy and Sell Stock with Transaction Fee
      • 718 Maximum Length of Repeated Subarray
      • 727 Minimum Window Subsequence
      • 730 Count Different Palindromic Subsequences
      • 740 Delete and Earn
      • 741 Cherry Pickup
      • 746 Min Cost Climbing Stairs
      • 750 Number Of Corner Rectangles
      • 764 Largest Plus Sign
      • 787 Cheapest Flights Within K Stops
      • 790 Domino and Tromino Tiling
      • 801 Minimum Swaps To Make Sequences Increasing
    • Union Find
      • 128 Longest Consecutive Sequence
      • 130 Surrounded Regions
      • 200 Number of Islands
      • 261 Graph Valid Tree
      • 305 Number of Islands II
      • 323 Number of Connected Components in an Undirected Graph
      • 547 Friend Circles
      • 684 Redundant Connection
      • 685 Redundant Connection II
      • 695 Max Area of Island
      • 721 Accounts Merge
      • 737 Sentence Similarity II
      • 765 Couples Holding Hands
      • 803 Bricks Falling When Hit
    • Scan Line
    • String
      • KMP
        • 28 Implement strStr()
        • 214 Shortest Palindrome
        • 459 Repeated Substring Pattern
        • 686 Repeated String Match
      • 271 Encode and Decode Strings
    • Reservoir Sampling
      • 382 Linked List Random Node
      • 398 Random Pick Index
    • Recursion
      • 678 Valid Parenthesis String
      • 736 Parse Lisp Expression
      • 761 Special Binary String
      • 779 K-th Symbol in Grammar
  • Google
    • 665 Non-decreasing Array
    • 400 Nth Digit
    • 484 Find Permutation
    • 353 Design Snake Game
    • 348 Design Tic-Tac-Toe
    • 657 Judge Route Circle
    • 789 Escape The Ghosts
    • 667 Beautiful Arrangement II
    • 359 Logger Rate Limiter
    • 463 Island Perimeter
    • 66 Plus One
    • 249 Group Shifted Strings
    • 281 Zigzag Iterator
    • 54 Spiral Matrix
    • 56 Merge Intervals
    • 57 Insert Interval
    • 163 Missing Ranges
    • 228 Summary Ranges
    • 166 Fraction to Recurring Decimal
    • 780 Reaching Points
    • 326 Power of Three
    • 318 Maximum Product of Word Lengths
    • 314 Binary Tree Vertical Order Traversal
    • 297 Serialize and Deserialize Binary Tree
    • 447 Number of Boomerangs
    • 362 Design Hit Counter
    • 448 Find All Numbers Disappeared in an Array
    • 409 Longest Palindrome
    • 406 Queue Reconstruction by Height
    • 370 Range Addition
    • 415 Add Strings
    • 498 Diagonal Traverse
    • 482 License Key Formatting
    • 560 Subarray Sum Equals K
    • 356 Line Reflection
    • 748 Shortest Completing Word
    • 218 The Skyline Problem
    • 391 Perfect Rectangle
    • 481 Magical String
    • 380 Insert Delete GetRandom O(1)
    • 800 Similar RGB Color
    • 246 Strobogrammatic Number
    • 247 Strobogrammatic Number II
    • 465 Optimal Account Balancing
    • 687 Longest Univalue Path
    • 543 Diameter of Binary Tree
    • 777 Swap Adjacent in LR String
    • 792 Number of Matching Subsequences
    • 460 LFU Cache
    • 779 K-th Symbol in Grammar
    • 289 Game of Life
    • 31 Next Permutation
    • 756 Pyramid Transition Matrix
    • 753 Cracking the Safe
    • 330 Patching Array
    • 327 Count of Range Sum
    • 769 Max Chunks To Make Sorted
    • 768 Max Chunks To Make Sorted II
    • 309 Best Time to Buy and Sell Stock with Cooldown
    • 393 UTF-8 Validation
    • 388 Longest Absolute File Path
    • 807 Max Increase to Keep City Skyline
    • 802 Find Eventual Safe States
    • 469 Convex Polygon
    • 683 K Empty Slots
    • 157 Read N Characters Given Read4
    • 158 Read N Characters Given Read4 II - Call multiple times
    • 681 Next Closest Time
    • 317 Shortest Distance from All Buildings
    • 587 Erect the Fence
    • 307 Range Sum Query - Mutable
    • 308 Range Sum Query 2D - Mutable
    • 282 Expression Add Operators
    • 616 Add Bold Tag in String
    • 497 Random Point in Non-overlapping Rectangles
    • 544 Output Contest Matches
    • 386 Lexicographical Numbers
Powered by GitBook
On this page
  • 803. Bricks Falling When Hit
  • 1. Question
  • 2. Implementation
  • 3. Time & Space Complexity

Was this helpful?

  1. Leetcode
  2. Union Find

803 Bricks Falling When Hit

Previous765 Couples Holding HandsNextScan Line

Last updated 5 years ago

Was this helpful?

803.

1. Question

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.

2. Implementation

(1) Union Find

思路: 这题题设是当brick通过hits数组打碎后,所有和第一行没有连在一起的brick就会掉落,问有多少brick会掉落。步骤如下:

(1) 我们可以用union find做。但union find只能连接不能断开,所以我们应该先处理hit brick之后的grid,找到所有connected component. 对于与第一行相连的component。我们用m * n这个特殊id表示和top连接的component, 因为按照row * n + col的方式定义union find的node id,m * n这个id是grid所有cell无法转换,非常适合做一个特殊id

(2) 找到hit之后的所有connected components后,我们倒过来把hit之后的brick加回去,每加一次的时候,查看和top连接的component的size,如果比之前的大,则有falling bricks,个数为newSize - size - 1,这里newSize是加上hit之后,与connected component的size,size是之前与top连接的component的size, 这里还要再减1是因为我们不算被hit的brick

class Solution {
    public int[] hitBricks(int[][] grid, int[][] hits) {
        if (grid == null || grid.length == 0) {
            return new int[0];
        }

        int m = grid.length;
        int n = grid[0].length;

        for (int[] hit : hits) {
            if (grid[hit[0]][hit[1]] == 1) {
                grid[hit[0]][hit[1]] = 2;
            }
        }

        UnionFind uf = new UnionFind(m *n + 1);
        int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

        // Get all connected components after the hit
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 1) {
                    connectNeighbors(i, j, uf, directions, grid);
                }
            }
        }

        // Find the original size of the component connected to the top
        int size = uf.size[uf.find(m * n)];
        int[] res = new int[hits.length];
        int newSize = 0; 

        // Reversely adding the hit brick to get size of connected component conencted to the top
        // The number of falling bricks of each hit will be the difference fo the size of the component connected to top
        for (int i = hits.length - 1; i >= 0; i--) {
            int[] hit = hits[i];
            if (grid[hit[0]][hit[1]] == 2) {
                connectNeighbors(hit[0], hit[1], uf, directions, grid);
                grid[hit[0]][hit[1]] = 1;
            }

            newSize = uf.size[uf.find(m * n)];
            if (newSize > size) {
                // we minus one here because the hit brick should not be counted
                res[i] = newSize - size - 1;
            }
            size = newSize;
        }
        return res;
    }

    // Connect brick in 4 directions
    public void connectNeighbors(int row, int col, UnionFind uf, int[][] directions, int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;

        for (int[] direction : directions) {
            int nextRow = row + direction[0];
            int nextCol = col + direction[1];

            if (isValid(nextRow, nextCol, grid)) {
                uf.union(row * n + col, nextRow * n + nextCol);
            }
        }

        // Use m * n as the special node id for connected component connected to the top row
        if (row == 0) {
            uf.union(row * n + col, m * n);
        }
    }

    public boolean isValid(int row, int col, int[][] grid) {
        return row >= 0 && row < grid.length && col >= 0 && col < grid[0].length && grid[row][col] == 1;
    }

    class UnionFind {
        int[] sets;
        int[] size;

        public UnionFind(int n) {
            sets = new int[n];
            size = new int[n];

            for (int i = 0; i < n; i++) {
                sets[i] = i;
                size[i] = 1;
            }
        }

        public int find(int node) {
            while (node != sets[node]) {
                node = sets[node];
            }
            return node;
        }

        public void union(int i, int j) {
            int node1 = find(i);
            int node2 = find(j);

            if (node1 == node2) {
                return;
            }

            sets[node1] = node2;
            size[node2] += size[node1];
        }
    }
}

3. Time & Space Complexity

Union Find: 时间复杂度O(mn * (k + mn)), k是hits数组的长度,unionfind里的find()最坏情况是O(mn), 在加上被hit的brick的过程中,我们每次都将被hit的brick的与四周union,这个过程要O(mn), 总共有k次,所以这步需要O(mnk). 另一部分时间是在刚开始找出在hit之后所有connected component的过程,这部分需要O(mn^2)。空间复杂度O(mn)

Bricks Falling When Hit