Created
June 23, 2022 21:39
-
-
Save alex700/955bcf9f160a73788ac70f29a70217bd to your computer and use it in GitHub Desktop.
Detect Number of Islands - LeetCode - Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
func main() { | |
var a = [][]int{ | |
{0, 0, 1, 1, 0}, | |
{0, 0, 1, 1, 0}, | |
{1, 0, 1, 0, 0}, | |
{1, 0, 1, 0, 0}, | |
} | |
fmt.Println("Number of islands:", numIslands(a)) | |
} | |
func markCurrentIsland(grid [][]int, x int, y int, r int, c int) { | |
if x < 0 || x >= r || y < 0 || y >= c || grid[x][y] != 1 { // Boundary case for matrix | |
return | |
} | |
// mark current cell as visited | |
grid[x][y] = 2 | |
markCurrentIsland(grid, x+1, y, r, c) // Down | |
markCurrentIsland(grid, x, y+1, r, c) // Right | |
markCurrentIsland(grid, x-1, y, r, c) // Top | |
markCurrentIsland(grid, x, y-1, r, c) // Left | |
} | |
func numIslands(grid [][]int) int { | |
var i, j int | |
var ( | |
noOfIslands = 0 | |
cols = len(grid[0]) | |
rows = len(grid) | |
) | |
if rows == 0 { // Empty grid boundary case | |
return 0 | |
} | |
// Iterate for all cells of the array | |
for i = 0; i < rows; i++ { | |
for j = 0; j < cols; j++ { | |
if grid[i][j] == 1 { | |
markCurrentIsland(grid, i, j, rows, cols) | |
noOfIslands++ | |
} | |
} | |
} | |
return noOfIslands | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment