- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to print number of islands in a given matrix using C#?
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
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
Advertisements
To Continue Learning Please Login
Login with Google