Grokking the Coding Interview: Patterns for Coding Questions

0% completed

Solution: Minimum Number of Days to Disconnect Island

Problem Statement

You are given a binary grid of size m x n, where each cell can either be land (marked as 1) or water (marked as 0). An island is a group of connected land cells (1s) that are adjacent either horizontally or vertically.

The grid is considered connected if it contains exactly one island.

In one day, we are allowed to change any single land cell 1 into a water cell 0.

Return the minimum number of days to disconnect the grid.

Examples

Example 1:

  • Input: grid =
    [[1, 1, 0], 
     [1, 1, 0], 
     [0, 1, 1]]
    

.....

.....

.....

Like the course? Get enrolled and start learning!
L

lejafilip

· 9 months ago

We just use indexes i and j but we need std::pair in parent to save the parent cell.

Otherwise the code is similar:

class Solution {     std::vector<std::pair<int, int>> DIRECTIONS = {{-1, 0}, {0, -1}, {1, 0}, {0, 1}};     bool isArticulationPoint = false; public:     int minDays(vector<vector<int>>& grid) {         int n = grid.size();         int m = grid[0].size();         std::vector<std::vector<int>> discoveryTime(n, std::vector<int>(m, -1));         std::vector<std::vector<int>> low(n, std::vector<int>(m, -1));         std::vector<std::vector<std::pair<int, int>>> parent(n, std::vector<std::pair<int, int>>(m, {-1, -1}));                 int islands = 0;         int totalLandCells = 0;         for(int i = 0; i < n; ++i)         {             for(int j = 0; j < m; ++j)