Skip to content

Instantly share code, notes, and snippets.

@alex700
Created June 23, 2022 21:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alex700/955bcf9f160a73788ac70f29a70217bd to your computer and use it in GitHub Desktop.
Save alex700/955bcf9f160a73788ac70f29a70217bd to your computer and use it in GitHub Desktop.
Detect Number of Islands - LeetCode - Go
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