Python | Easy | Heap | Trapping Rain Water II
\nsee the Successfully Accepted Submission\nPython\nclass Solution:\n    def trapRainWater(self, heightMap: List[List[int]]) -> int:\n        # Check if heightM
\n[see the Successfully Accepted Submission](https://leetcode.com/submissions/detail/1069470635/)\n```Python\nclass Solution:\n    def trapRainWater(self, heightMap: List[List[int]]) -> int:\n        # Check if heightMap is empty\n        if not heightMap:\n            return 0\n\n        # Get the dimensions of the heightMap\n        m, n = len(heightMap), len(heightMap[0])\n\n        # Define the maximum height possible\n        max_height = 2 * 10**4\n\n        # Define directions for neighboring cells\n        directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n\n        # Helper function to check if a cell is within the map\n        def is_in_map(row, col):\n            return 0 <= row < m and 0 <= col < n\n\n        # Depth-first search (DFS) function to process water flow\n        def dfs(row, col):\n            if not is_in_map(row, col):\n                return\n\n            if heightMap[row][col] != 0:\n                return\n\n            for dir_row, dir_col in directions:\n                next_row, next_col = row + dir_row, col + dir_col\n                if not is_in_map(next_row, next_col) or heightMap[next_row][next_col] == -1:\n                    nonlocal curr_water\n                    curr_water -= 1\n                    heightMap[row][col] = -1\n                    break\n\n            if heightMap[row][col] == 0:\n                return\n\n            for dir_row, dir_col in directions:\n                next_row, next_col = row + dir_row, col + dir_col\n                dfs(next_row, next_col)\n\n        ans = 0\n        curr_water = 0\n        coordinates = {}\n\n        # Create a dictionary to store coordinates of cells with the same height\n        for row in range(m):\n            for col in range(n):\n                h = heightMap[row][col]\n                if h not in coordinates:\n                    coordinates[h] = []\n                coordinates[h].append((row, col))\n\n        # Iterate through possible heights\n        for height in range(max_height + 1):\n            if height in coordinates:\n                for row, col in coordinates[height]:\n                    heightMap[row][col] = 0\n                    curr_water += 1\n                    dfs(row, col)\n\n            ans += curr_water\n\n        return ans\n\n```\n\n![image](https://assets.leetcode.com/users/images/b1e4af48-4da1-486c-bc97-b11ae02febd0_1696186577.992237.jpeg)\n
['Heap (Priority Queue)', 'Python']