C++ Program to find the number of Islands using DFSA typical algorithmic issue that frequently arises in graph theory and image processing is the need for a C++ program to count the number of islands using Depth-First Search (DFS). In this article, we will discuss the C++ program to find the number of islands using DFS. Example:Let's take an example to demonstrate how to find the number of islands using DFS in C++. Output: Number of islands: 3 Explanation: 1. Solution Class In this example, the solution class is the answer to determining how many islands are contained in this class. numIslands and dfs are the two main approaches that are present in this class. 2. numIslands Method This method is used to define the number of islands in the binary matrix. It accepts as a parameter a binary matrix represented by a 2D vector grid. It initializes and sets to 0 an integer variable called num to keep track of the variety of islands. 3. Edge Case Check The input grid's edge cases, where it is empty or has empty rows, are checked. It returns 0 if either of the conditions is true, signifying that there are no islands. 4. The Grid Iteratively In the approach, nested loops are used to traverse over the full binary matrix. Both the inner and the outer loops iterate across the columns and rows. 5. A DFS for Islands In the matrix, the beginning of a new island is indicated by the presence of a "1" (which denotes land) at coordinates (i, j). After that, the method invokes the dfs method to conduct a Depth-First Search to mark the entire island as visited. It increases the num variable to count the island after marking it. 6. dfs Method
7. main Function The definition of a sample binary matrix (grid) is contained in the main function. Next, the solution class instance is generated. The numIslands technique is used to calculate the number of islands. After that, the output is the total number of islands. 8. Output The program prints the number of islands that were discovered in the binary matrix. Complexity:
Conclusion:In conclusion, a C++ program to count the number of islands using DFS is a useful tool for locating linked clusters of '1's in a binary matrix. It uses the DFS algorithm to effectively navigate the matrix and count the number of islands. Next TopicClamp in C++ |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India