Given a binary matrix mat[][] of dimensions NxM such that 1 denotes the island and 0 denotes the water. The task is to find the number of closed islands in the given matrix.
A closed island is known as the group of 1s that is surrounded by only 0s on all the four sides (excluding diagonals). If any 1 is at the edges of the given matrix then it is not considered as the part of the connected island as it is not surrounded by all 0.
Examples:
Input: N = 5, M = 8,
mat[][] =
{{0, 0, 0, 0, 0, 0, 0, 1},
{0, 1, 1, 1, 1, 0, 0, 1},
{0, 1, 0, 1, 0, 0, 0, 1},
{0, 1, 1, 1, 1, 0, 1, 0},
{0, 0, 0, 0, 0, 0, 0, 1}}
Output: 2
Explanation:
mat[][] =
{{0, 0, 0, 0, 0, 0, 0, 1},
{0, 1, 1, 1, 1, 0, 0, 1},
{0, 1, 0, 1, 0, 0, 0, 1},
{0, 1, 1, 1, 1, 0, 1, 0},
{0, 0, 0, 0, 0, 0, 0, 1}}
There are 2 closed islands.
The islands in dark are closed because they are completely surrounded by
0s (water).
There are two more islands in the last column of the matrix, but they are not completely surrounded by 0s.
Hence they are not closed islands.
Input: N = 3, M = 3, matrix[][] =
{{1, 0, 0},
{0, 1, 0},
{0, 0, 1}}
Output: 1
Method 1 – using DFS Traversal: The idea is to use DFS Traversal to count the number of island surrounded by water. But we have to keep the track of the island at the corner of the given matrix as they will not be counted in the resultant island. Below are the steps:
- Initialize a 2D visited matrix(say vis[][]) to keep the track of traversed cell in the given matrix.
- Perform DFS Traversal on all the corner of the given matrix and if any element has value 1 then marked all the cell with value 1 as visited because it cannot be counted in the resultant count.
- Perform DFS Traversal on all the remaining unvisted cell and if value encountered is 1 then marked this cell as visited, count this island in the resultant count and recursively call DFS for all the 4 directions i.e., left, right, top, and bottom to make all the 1s connected to the current cell as visited.
- Repeat the above step untill all cell with value 1 are not visited.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;// DFS Traversal to find the count of// island surrounded by watervoid dfs(vector<vector<int> >& matrix, vector<vector<bool> >& visited, int x, int y, int n, int m){ // If the land is already visited // or there is no land or the // coordinates gone out of matrix // break function as there // will be no islands if (x < 0 || y < 0 || x >= n || y >= m || visited[x][y] == true || matrix[x][y] == 0) return; // Mark land as visited visited[x][y] = true; // Traverse to all adjacent elements dfs(matrix, visited, x + 1, y, n, m); dfs(matrix, visited, x, y + 1, n, m); dfs(matrix, visited, x - 1, y, n, m); dfs(matrix, visited, x, y - 1, n, m);}// Function that counts the closed islandint countClosedIsland(vector<vector<int> >& matrix, int n, int m){ // Create boolean 2D visited matrix // to keep track of visited cell // Initially all elements are // unvisited. vector<vector<bool> > visited(n, vector<bool>(m, false)); // Mark visited all lands // that are reachable from edge for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { // Traverse corners if ((i * j == 0 || i == n - 1 || j == m - 1) and matrix[i][j] == 1 and visited[i][j] == false) dfs(matrix, visited, i, j, n, m); } } // To stores number of closed islands int result = 0; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { // If the land not visited // then there will be atleast // one closed island if (visited[i][j] == false and matrix[i][j] == 1) { result++; // Mark all lands associated // with island visited. dfs(matrix, visited, i, j, n, m); } } } // Return the final count return result;}// Driver Codeint main(){ // Given size of Matrix int N = 5, M = 8; // Given Matrix vector<vector<int> > matrix = { { 0, 0, 0, 0, 0, 0, 0, 1 }, { 0, 1, 1, 1, 1, 0, 0, 1 }, { 0, 1, 0, 1, 0, 0, 0, 1 }, { 0, 1, 1, 1, 1, 0, 1, 0 }, { 0, 0, 0, 0, 0, 0, 0, 1 } }; // Function Call cout << countClosedIsland(matrix, N, M); return 0;} |
Java
// Java program for the above approachimport java.util.*;class GFG { // DFS Traversal to find the count of // island surrounded by water static void dfs(int[][] matrix, boolean[][] visited, int x, int y, int n, int m) { // If the land is already visited // or there is no land or the // coordinates gone out of matrix // break function as there // will be no islands if (x < 0 || y < 0 || x >= n || y >= m || visited[x][y] == true || matrix[x][y] == 0) return; // Mark land as visited visited[x][y] = true; // Traverse to all adjacent elements dfs(matrix, visited, x + 1, y, n, m); dfs(matrix, visited, x, y + 1, n, m); dfs(matrix, visited, x - 1, y, n, m); dfs(matrix, visited, x, y - 1, n, m); } // Function that counts the closed island static int countClosedIsland(int[][] matrix, int n, int m) { // Create boolean 2D visited matrix // to keep track of visited cell // Initially all elements are // unvisited. boolean[][] visited = new boolean[n][m]; // Mark visited all lands // that are reachable from edge for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { // Traverse corners if ((i * j == 0 || i == n - 1 || j == m - 1) && matrix[i][j] == 1 && visited[i][j] == false) dfs(matrix, visited, i, j, n, m); } } // To stores number of closed islands int result = 0; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { // If the land not visited // then there will be atleast // one closed island if (visited[i][j] == false && matrix[i][j] == 1) { result++; // Mark all lands associated // with island visited. dfs(matrix, visited, i, j, n, m); } } } // Return the final count return result; } // Driver Code public static void main(String[] args) { // Given size of Matrix int N = 5, M = 8; // Given Matrix int[][] matrix = { { 0, 0, 0, 0, 0, 0, 0, 1 }, { 0, 1, 1, 1, 1, 0, 0, 1 }, { 0, 1, 0, 1, 0, 0, 0, 1 }, { 0, 1, 1, 1, 1, 0, 1, 0 }, { 0, 0, 0, 0, 0, 0, 0, 1 } }; // Function Call System.out.print(countClosedIsland(matrix, N, M)); }}// This code is contributed by Rohit_ranjan |
C#
// C# program for the above approachusing System;class GFG { // DFS Traversal to find the count of // island surrounded by water static void dfs(int[, ] matrix, bool[, ] visited, int x, int y, int n, int m) { // If the land is already visited // or there is no land or the // coordinates gone out of matrix // break function as there // will be no islands if (x < 0 || y < 0 || x >= n || y >= m || visited[x, y] == true || matrix[x, y] == 0) return; // Mark land as visited visited[x, y] = true; // Traverse to all adjacent elements dfs(matrix, visited, x + 1, y, n, m); dfs(matrix, visited, x, y + 1, n, m); dfs(matrix, visited, x - 1, y, n, m); dfs(matrix, visited, x, y - 1, n, m); } // Function that counts the closed island static int countClosedIsland(int[, ] matrix, int n, int m) { // Create bool 2D visited matrix // to keep track of visited cell // Initially all elements are // unvisited. bool[, ] visited = new bool[n, m]; // Mark visited all lands // that are reachable from edge for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { // Traverse corners if ((i * j == 0 || i == n - 1 || j == m - 1) && matrix[i, j] == 1 && visited[i, j] == false) dfs(matrix, visited, i, j, n, m); } } // To stores number of closed islands int result = 0; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { // If the land not visited // then there will be atleast // one closed island if (visited[i, j] == false && matrix[i, j] == 1) { result++; // Mark all lands associated // with island visited. dfs(matrix, visited, i, j, n, m); } } } // Return the readonly count return result; } // Driver Code public static void Main(String[] args) { // Given size of Matrix int N = 5, M = 8; // Given Matrix int[, ] matrix = { { 0, 0, 0, 0, 0, 0, 0, 1 }, { 0, 1, 1, 1, 1, 0, 0, 1 }, { 0, 1, 0, 1, 0, 0, 0, 1 }, { 0, 1, 1, 1, 1, 0, 1, 0 }, { 0, 0, 0, 0, 0, 0, 0, 1 } }; // Function call Console.Write(countClosedIsland(matrix, N, M)); }}// This code is contributed by amal kumar choubey |
2
Time Complexity: O(N*M)
Auxiliary Space: O(N*M)
Method: Single DFS Traversal
Improvement over Method 1: In the above Method 1, we see that we are calling DFS traversal twice (Once over the corner cells with ‘1’ and afterwards over the cells which are not on the corners with ‘1’ and are not visited). We can solve this using only 1 DFS traversal. the idea is to call DFS for the cells with value ‘1’ which are not on the corners and while doing so, if we find a cell with value ‘1’ on the corner, then that means it should not be counted as an island. The code is shown below:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;// DFS Traversal to find the count of// island surrounded by watervoid dfs(vector<vector<int> >& matrix, vector<vector<bool> >& visited, int x, int y, int n, int m, bool &hasCornerCell;){ // If the land is already visited // or there is no land or the // coordinates gone out of matrix // break function as there // will be no islands if (x < 0 || y < 0 || x >= n || y >= m || visited[x][y] == true || matrix[x][y] == 0) return; // Check for the corner cell if(x == 0 || y == 0 || x == n-1 || y == m-1) { if(matrix[x][y] == 1) hasCornerCell = true; } // Mark land as visited visited[x][y] = true; // Traverse to all adjacent elements dfs(matrix, visited, x + 1, y, n, m, hasCornerCell); dfs(matrix, visited, x, y + 1, n, m, hasCornerCell); dfs(matrix, visited, x - 1, y, n, m, hasCornerCell); dfs(matrix, visited, x, y - 1, n, m, hasCornerCell);}// Function that counts the closed islandint countClosedIsland(vector<vector<int> >& matrix, int n, int m){ // Create boolean 2D visited matrix // to keep track of visited cell // Initially all elements are // unvisited. vector<vector<bool>> visited(n,vector<bool>(m, false)); // Store the count of islands int result = 0; // Call DFS on the cells which // are not on corners with value '1' for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if ((i != 0 && j != 0 && i != n - 1 && j != m - 1) and matrix[i][j] == 1 and visited[i][j] == false) { // Determine if the island is closed bool hasCornerCell = false; /* hasCornerCell will be updated to true while DFS traversal if there is a cell with value '1' on the corner */ dfs(matrix, visited, i, j, n, m, hasCornerCell); /* If the island is closed*/ if(!hasCornerCell) result = result + 1; } } } // Return the final count return result;}// Driver Codeint main(){ // Given size of Matrix int N = 5, M = 8; // Given Matrix vector<vector<int> > matrix = { { 0, 0, 0, 0, 0, 0, 0, 1 }, { 0, 1, 1, 1, 1, 0, 0, 1 }, { 0, 1, 0, 1, 0, 0, 0, 1 }, { 0, 1, 1, 1, 1, 0, 1, 0 }, { 0, 0, 0, 0, 0, 0, 0, 1 } }; // Function Call cout << countClosedIsland(matrix, N, M); return 0;} |
2
Method 2 – using BFS Traversal: The idea is to visit every cell with value 1 at the corner using BFS and then traverse the given matrix and if any unvisited cell with value 1 is encountered then increment the count of the island and make all the 1s connected to it as visited. Below are the steps:
- Initialize a 2D visited matrix(say vis[][]) to keep the track of traversed cell in the given matrix.
- Perform BFS Traversal on all the corner of the given matrix and if any element has value 1 then marked all the cell with value 1 as visited because it cannot be counted in the resultant count.
- Perform BFS Traversal on all the remaining unvisted cell and if value encountered is 1 then marked this cell as visited, count this island in the resultant count and marked every cell in all the 4 directions i.e., left, right, top, and bottom to make all the 1s connected to the current cell as visited.
- Repeat the above step until all cell with value 1 are not visited.
- Print the count of island after the above steps.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;int dx[] = { -1, 0, 1, 0 };int dy[] = { 0, 1, 0, -1 };// DFS Traversal to find the count of// island surrounded by watervoid bfs(vector<vector<int> >& matrix, vector<vector<bool> >& visited, int x, int y, int n, int m){ // To store the popped cell pair<int, int> temp; // To store the cell of BFS queue<pair<int, int> > Q; // Push the current cell Q.push({ x, y }); // Until Q is not empty while (!Q.empty()) { temp = Q.front(); Q.pop(); // Mark current cell // as visited visited[temp.first] [temp.second] = true; // Iterate in all four directions for (int i = 0; i < 4; i++) { int x = temp.first + dx[i]; int y = temp.second + dy[i]; // Cell out of the matrix if (x < 0 || y < 0 || x >= n || y >= m || visited[x][y] == true || matrix[x][y] == 0) { continue; } // Check is adjacent cell is // 1 and not visited if (visited[x][y] == false && matrix[x][y] == 1) { Q.push({ x, y }); } } }}// Function that counts the closed islandint countClosedIsland(vector<vector<int> >& matrix, int n, int m){ // Create boolean 2D visited matrix // to keep track of visited cell // Initially all elements are // unvisited. vector<vector<bool> > visited( n, vector<bool>(m, false)); // Mark visited all lands // that are reachable from edge for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { // Traverse corners if ((i * j == 0 || i == n - 1 || j == m - 1) and matrix[i][j] == 1 and visited[i][j] == false) { bfs(matrix, visited, i, j, n, m); } } } // To stores number of closed islands int result = 0; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { // If the land not visited // then there will be atleast // one closed island if (visited[i][j] == false and matrix[i][j] == 1) { result++; // Mark all lands associated // with island visited bfs(matrix, visited, i, j, n, m); } } } // Return the final count return result;}// Driver Codeint main(){ // Given size of Matrix int N = 5, M = 8; // Given Matrix vector<vector<int> > matrix = { { 0, 0, 0, 0, 0, 0, 0, 1 }, { 0, 1, 1, 1, 1, 0, 0, 1 }, { 0, 1, 0, 1, 0, 0, 0, 1 }, { 0, 1, 1, 1, 1, 0, 1, 0 }, { 0, 0, 0, 0, 0, 0, 0, 1 } }; // Function Call cout << countClosedIsland(matrix, N, M); return 0;} |
2
Time Complexity: O(N*M)
Auxiliary Space: O(N*M)
Method 3 – using Disjoint-Set(Union-Find):
- Traverse the given matrix and change all the 1s and connected at the corners of the matrix to 0s.
- Now traverse the matrix again, and for all set of connected 1s create an edges connecting to all the 1s.
- Find the connected components for all the edges stored using Disjoint-Set Approach.
- Print the count of components after the above steps.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;// Function that implements the Findint Find(vector<int>& hashSet, int val){ // Get the val int parent = val; // Until parent is not found while (parent != hashSet[parent]) { parent = hashSet[parent]; } // Return the parent return parent;}// Function that implements the Unionvoid Union(vector<int>& hashSet, int first, int second){ // Find the first father int first_father = Find(hashSet, first); // Find the second father int second_father = Find(hashSet, second); // If both are unequals then update // first father as ssecond_father if (first_father != second_father) hashSet[first_father] = second_father;}// Recursive Function that change all// the corners connected 1s to 0svoid change(vector<vector<char> >& matrix, int x, int y, int n, int m){ // If already zero then return if (x < 0 || y < 0 || x > m - 1 || y > n - 1 || matrix[x][y] == '0') return; // Change the current cell to '0' matrix[x][y] = '0'; // Recursive Call for all the // four corners change(matrix, x + 1, y, n, m); change(matrix, x, y + 1, n, m); change(matrix, x - 1, y, n, m); change(matrix, x, y - 1, n, m);}// Function that changes all the// connected 1s to 0s at the cornersvoid changeCorner(vector<vector<char> >& matrix){ // Dimensions of matrix int m = matrix.size(); int n = matrix[0].size(); // Traverse the matrix for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { // If corner cell if (i * j == 0 || i == m - 1 || j == n - 1) { // If value is 1s, then // recursively change to 0 if (matrix[i][j] == '1') { change(matrix, i, j, n, m); } } } }}// Function that counts the number// of island in the given matrixint numIslands(vector<vector<char> >& matrix){ if (matrix.size() == 0) return 0; // Dimensions of the matrix int m = matrix.size(); int n = matrix[0].size(); // Make all the corners connecting // 1s to zero changeCorner(matrix); // First convert to 1 dimension // position and convert all the // connections to edges vector<pair<int, int> > edges; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { // If the cell value is 1 if (matrix[i][j] == '1') { int id = i * n + j; // Move right if (j + 1 < n) { // If right cell is // 1 then make it as // an edge if (matrix[i][j + 1] == '1') { int right = i * n + j + 1; // Push in edge vector edges.push_back(make_pair(id, right)); } } // Move down if (i + 1 < m) { // If right cell is // 1 then make it as // an edge if (matrix[i + 1][j] == '1') { int down = (i + 1) * n + j; // Push in edge vector edges.push_back(make_pair(id, down)); } } } } } // Construct the Union Find structure vector<int> hashSet(m * n, 0); for (int i = 0; i < m * n; i++) { hashSet[i] = i; } // Next apply Union Find for all // the edges stored for (auto edge : edges) { Union(hashSet, edge.first, edge.second); } // To count the number of connected // islands int numComponents = 0; // Traverse to find the islands for (int i = 0; i < m * n; i++) { if (matrix[i / n][i % n] == '1' && hashSet[i] == i) numComponents++; } // Return the count of the island return numComponents;}// Driver Codeint main(){ // Given size of Matrix int N = 5, M = 8; // Given Matrix vector<vector<char> > matrix = { { '0', '0', '0', '0', '0', '0', '0', '1' }, { '0', '1', '1', '1', '1', '0', '0', '1' }, { '0', '1', '0', '1', '0', '0', '0', '1' }, { '0', '1', '1', '1', '1', '0', '1', '0' }, { '0', '0', '0', '0', '0', '0', '0', '1' } }; // Function Call cout << numIslands(matrix); return 0;} |
2
Time Complexity: O(N*M)
Auxiliary Space: O(N*M)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Find the number of distinct islands in a 2D matrix
- Find the number of islands | Set 1 (Using DFS)
- Find the number of Islands | Set 2 (Using Disjoint Set)
- Count number of islands where every island is row-wise and column-wise separated
- Minimum number of Water to Land conversion to make two islands connected in a Grid
- Islands in a graph using BFS
- Check if a given matrix can be converted to another given matrix by row and column exchanges
- Minimum number of steps to convert a given matrix into Upper Hessenberg matrix
- Minimum number of steps to convert a given matrix into Diagonally Dominant Matrix
- Find trace of matrix formed by adding Row-major and Column-major order of same matrix
- Maximize sum of N X N upper left sub-matrix from given 2N X 2N matrix
- Check if it is possible to make the given matrix increasing matrix or not
- Program to convert given Matrix to a Diagonal Matrix
- Maximum trace possible for any sub-matrix of the given matrix
- Convert given Matrix into sorted Spiral Matrix
- Minimize count of adjacent row swaps to convert given Matrix to a Lower Triangular Matrix
- Construct a Matrix such that each cell consists of sum of adjacent elements of respective cells in given Matrix
- Find row with maximum and minimum number of zeroes in given Matrix
- Find row number of a binary matrix having maximum number of 1s
- Circular Matrix (Construct a matrix with numbers 1 to m*n in spiral way)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

