


‘N’ = 3, ‘M’ = 3
‘GRID’ =

We can disconnect the ‘GRID’ by removing the cities at locations ‘(0, 1)’ and ‘(0, 2)’. Thus, you should return ‘2’ as the answer.
1. A ‘GRID’ with zero cities is also disconnected.
2. You do not need to print anything; it has already been taken care of. Just implement the function.
The first line of input contains an integer ‘T’ which denotes the number of test cases. Then, the ‘T’ test cases follow.
Each test case’s first line contains two integers, ‘N’ and ‘M’, denoting the number of rows and columns in ‘GRID’. Then, ‘N’ lines follow.
Each line contains an ‘M’ space-separated integers denoting each row’s values in ‘GRID’.
For every test case, return the minimum number of cities to remove to disconnect the island.
1 <= T <= 10
1 <= N, M <= 100
Value in each element of ‘GRID’ = [0, 1]
Where ‘T’ is the number of test cases, ‘N’ is the number of rows in ‘GRID’, and ‘M’ is the number of columns in ‘GRID’.
Time limit: 1 second
Observation: The answer is always less than equal to two (‘<= 2’).
Proof: For any state (with ‘>= 3’ cities), every city at its boundary is connected to ‘<= 3’ cities, and between those cities, there will be at least one city connected to exactly two other cities. This city (colored red) can be of one of the following four types:
If we remove the two grey-colored cities, then the city with red color will get disconnected from its state. Now, we know that the answer will never be greater than ‘2’.
To check if the ‘GRID’ is disconnected, we can do a Depth-first search (or Breadth-first search) traversal for any arbitrary city and mark all the reachable cities from it. If some cities remain unmarked, then the ‘GRID’ is disconnected.
We try to find if the ‘GRID’ can be disconnected by removing:
The ‘isDisconnected()’ function to check if the ‘GRID’ is disconnected:
The ‘dfs(integer x, integer y)’ function to mark all the cities connected to ‘(x, y)’:
Algorithm:
An articulation point (or cut vertex) is defined as a vertex that, when removed along with associated edges, makes the graph disconnected (or, more precisely, increases the number of connected components in the graph).
We can find the articulation point by doing a Depth-first search traversal (DFS) of the graph. A node ‘u’ is said to be an articulation point if:
Refer to this for detailed implementation: Finding articulation points in ‘O(V + E)’, where ‘V’ is the number of vertices and ‘E’ is the number of edges in the graph.
Let ‘count’ be the number of cities in the ‘GRID’. If the ‘GRID’ contains ‘0’ cities (‘count = 0’), then the answer is ‘0’. If the ‘GRID’ contains only ‘1’ city (‘count = 1’), we can remove this city to make the ‘GRID’ disconnected, so the answer is ‘1’. So, for ‘count <= 1’, the answer is equal to ‘count’.
Algorithm: