iT邦幫忙

2024 iThome 鐵人賽

DAY 11
0
佛心分享-刷題不只是刷題

8月 LeetCode Daily 見聞錄系列 第 11

[8/11] 1568. Minimum Number of Days to Disconnect Island

  • 分享至 

  • xImage
  •  

Hard
Related Topics: Array / DFS / BFS / Matrix / Strongly Connected Component
LeetCode Source

解題想法

主要是找出最少需要多少天才能將二維網格中的所有陸地(即值為1的區域)連成一片。

首先,它會計算網格中有多少個獨立的島嶼。

如果有多個島嶼,則返回0,表示無法只用一天將它們連成一片。

如果只有一個島嶼,則逐個檢查每個陸地格子,嘗試將其設為0並檢查是否仍然只有一個島嶼。

如果在這種情況下島嶼數量變多,則需要1天來使它們連成一片;如果沒有變化,則至少需要2天。

Complexity

Time Complexity: O(m * n * (m + n))
Space Complexity: O(m * n)

Python

class Solution:
    def minDays(self, grid: List[List[int]]) -> int:
        def count_islands():
            seen = set()
            
            def dfs(r, c):
                stack = [(r, c)]
                while stack:
                    x, y = stack.pop()
                    for nx, ny in [(x-1, y), (x+1, y), (x, y-1), (x, y+1)]:
                        if 0 <= nx < len(grid) and 0 <= ny < len(grid[0]) and grid[nx][ny] == 1 and (nx, ny) not in seen:
                            seen.add((nx, ny))
                            stack.append((nx, ny))
            
            islands = 0
            for i in range(len(grid)):
                for j in range(len(grid[0])):
                    if grid[i][j] == 1 and (i, j) not in seen:
                        islands += 1
                        seen.add((i, j))
                        dfs(i, j)
            return islands
        
        if count_islands() != 1:
            return 0
        
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if grid[i][j] == 1:
                    grid[i][j] = 0
                    if count_islands() != 1:
                        return 1
                    grid[i][j] = 1
        
        return 2

C++

class Solution {
public:
    int minDays(vector<vector<int>>& grid) {
        auto count_islands = [&]() -> int {
            vector<vector<int>> seen(grid.size(), vector<int>(grid[0].size(), 0));
            int islands = 0;
            
            function<void(int, int)> dfs = [&](int r, int c) {
                seen[r][c] = 1;
                for (auto [dr, dc] : {pair{-1, 0}, {1, 0}, {0, -1}, {0, 1}}) {
                    int nr = r + dr, nc = c + dc;
                    if (nr >= 0 && nr < grid.size() && nc >= 0 && nc < grid[0].size() && grid[nr][nc] == 1 && !seen[nr][nc]) {
                        dfs(nr, nc);
                    }
                }
            };
            
            for (int i = 0; i < grid.size(); i++) {
                for (int j = 0; j < grid[0].size(); j++) {
                    if (grid[i][j] == 1 && !seen[i][j]) {
                        islands++;
                        dfs(i, j);
                    }
                }
            }
            return islands;
        };
        
        if (count_islands() != 1) return 0;
        
        for (int i = 0; i < grid.size(); i++) {
            for (int j = 0; j < grid[0].size(); j++) {
                if (grid[i][j] == 1) {
                    grid[i][j] = 0;
                    if (count_islands() != 1) return 1;
                    grid[i][j] = 1;
                }
            }
        }
        
        return 2;
    }
};

上一篇
[8/10] 959. Regions Cut By Slashes
下一篇
[8/12] 703. Kth Largest Element in a Stream
系列文
8月 LeetCode Daily 見聞錄30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言