0ms Solution in C using DFS


  • 1
    C
    #include<stdio.h>
    #include<stdlib.h>
    
    void my_numIslands(char** grid, int gridRowSize, int gridColSize, int row, int col) 
    {
        grid[row][col] = '0';
        if (row - 1 >= 0 && grid[row - 1][col] == '1') my_numIslands(grid, gridRowSize, gridColSize, row - 1, col);
        if (row + 1 < gridRowSize && grid[row + 1][col] == '1') my_numIslands(grid, gridRowSize, gridColSize, row + 1, col);
        if (col - 1 >= 0 && grid[row][col - 1] == '1') my_numIslands(grid, gridRowSize, gridColSize, row, col - 1);
        if (col + 1 < gridColSize && grid[row][col + 1] == '1') my_numIslands(grid, gridRowSize, gridColSize, row, col + 1);
    }
    
    int numIslands(char** grid, int gridRowSize, int gridColSize) 
    {
    	    int i, j;
    
            int count = 0;
    
        for (i = 0; i < gridRowSize; ++i)
        {
        	    for (j = 0; j < gridColSize; ++j)
    	    {
    		    if (grid[i][j] == '1')
    		    {
    			    my_numIslands(grid, gridRowSize, gridColSize, i, j);
    			    ++count;
    		    }
    	    }
        }
    
        return count;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.