How to print number of islands in a given matrix using C#?

CsharpServer Side ProgrammingProgramming

Linear scan the 2d grid map, if a node contains a '1', then it is a root node that triggers a Depth First Search. During DFS, every visited node should be set as '0' to mark as visited node. Count the number of root nodes that trigger DFS, this number would be the number of islands since each DFS starting at some root identifies an island.

Example

 Live Demo

using System;
namespace ConsoleApplication{
   public class Matrix{
      public int PrintNumberOfIslands(char[,] grid){
         bool[,] visited = new bool[grid.GetLength(0), grid.GetLength(1)];
         int res = 0;
         for (int i = 0; i < grid.GetLength(0); i++){
            for (int j = 0; j < grid.GetLength(1); j++){
               if (grid[i, j] == '1' && !visited[i, j]){
                  DFS(grid, visited, i, j);
                  res++;
               }
            }
         }
         return res;
      }
      public void DFS(char[,] grid, bool[,] visited, int i, int j){
         if (i < 0 || i >= grid.GetLength(0)) return;
         if (j < 0 || j >= grid.GetLength(1)) return;
         if (grid[i, j] != '1' || visited[i, j]) return;
         visited[i, j] = true;
         DFS(grid, visited, i + 1, j);
         DFS(grid, visited, i - 1, j);
         DFS(grid, visited, i, j + 1);
         DFS(grid, visited, i, j - 1);
      }
   }
   class Program{
      static void Main(string[] args){
         Matrix m = new Matrix();
         char[,] mm = { { '1', '1', '1', '1', '0' }, { '1', '1', '0', '1', '0' }, { '1', '1', '0', '0', '0' }, { '0', '0', '0', '0', '1' } };
         Console.WriteLine(m.PrintNumberOfIslands(mm));
      }
   }
}

Output

2
raja
Published on 27-Aug-2021 13:10:01
Advertisements