Number of Islands | LeetCode

class Solution {
public int numIslands(char[][] grid) {

int m = grid.length;
int n = grid[0].length;

int countIsland = 0;

for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if(grid[…


This content originally appeared on DEV Community and was authored by Tanuja V

class Solution {
    public int numIslands(char[][] grid) {

        int m = grid.length;
        int n = grid[0].length;

        int countIsland = 0;

        for(int i=0; i<m; i++){
            for(int j=0; j<n; j++){
                if(grid[i][j]=='1'){
                    dfs(grid, i, j);
                    countIsland++;
                }
            }
        }

        return countIsland;
    }

    void dfs(char grid[][], int i, int j){
        if(i<0 || j<0 || i>=grid.length || j>=grid[0].length || grid[i][j]=='0' || grid[i][j] == '2')
            return;

        grid[i][j] = '2';

        dfs(grid, i+1, j);
        dfs(grid, i-1, j);
        dfs(grid, i, j+1);
        dfs(grid, i, j-1);
    }
}

Thanks for reading :)
Feel free to comment and like the post if you found it helpful
Follow for more 🤝 && Happy Coding 🚀

If you enjoy my content, support me by following me on my other socials:
https://linktr.ee/tanujav7


This content originally appeared on DEV Community and was authored by Tanuja V


Print Share Comment Cite Upload Translate Updates
APA

Tanuja V | Sciencx (2024-06-19T06:15:31+00:00) Number of Islands | LeetCode. Retrieved from https://www.scien.cx/2024/06/19/number-of-islands-leetcode/

MLA
" » Number of Islands | LeetCode." Tanuja V | Sciencx - Wednesday June 19, 2024, https://www.scien.cx/2024/06/19/number-of-islands-leetcode/
HARVARD
Tanuja V | Sciencx Wednesday June 19, 2024 » Number of Islands | LeetCode., viewed ,<https://www.scien.cx/2024/06/19/number-of-islands-leetcode/>
VANCOUVER
Tanuja V | Sciencx - » Number of Islands | LeetCode. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/06/19/number-of-islands-leetcode/
CHICAGO
" » Number of Islands | LeetCode." Tanuja V | Sciencx - Accessed . https://www.scien.cx/2024/06/19/number-of-islands-leetcode/
IEEE
" » Number of Islands | LeetCode." Tanuja V | Sciencx [Online]. Available: https://www.scien.cx/2024/06/19/number-of-islands-leetcode/. [Accessed: ]
rf:citation
» Number of Islands | LeetCode | Tanuja V | Sciencx | https://www.scien.cx/2024/06/19/number-of-islands-leetcode/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.