Skip to content

Instantly share code, notes, and snippets.

@coxley
Last active July 27, 2022 04:11
Show Gist options
  • Save coxley/fe66f5b2d78496764087c595bc02b215 to your computer and use it in GitHub Desktop.
Save coxley/fe66f5b2d78496764087c595bc02b215 to your computer and use it in GitHub Desktop.
Problem: Number of Islands
// Problem: https://leetcode.com/problems/number-of-islands/
// ASCII byte reference
// 48 = "0"
// 49 = "1"
// 120 = "x"
package main
import "fmt"
func findBounds(input [][]byte, row, col int) int {
if row < 0 || row >= len(input) {
return 0
} else if col < 0 || col >= len(input[row]) {
return 0
} else if input[row][col] != 49 {
return 0
}
var contiguous int = 1
input[row][col] = 120
contiguous += findBounds(input, row+1, col)
contiguous += findBounds(input, row-1, col)
contiguous += findBounds(input, row, col+1)
contiguous += findBounds(input, row, col-1)
return contiguous
}
func numIslands(input [][]byte) int {
var islands int
for row := range input {
for col := range input[row] {
if input[row][col] != 49 {
continue
}
// Once land is encountered, mark all contiguous blocks with an "x"
findBounds(input, row, col)
islands++
}
}
return islands
}
func main() {
// Leetcode gives the input is a 2d byte slice so
// using the ASCII values for '0', '1', and 'x'
var input = [][]byte{
{49, 49, 48, 48, 48},
{49, 49, 48, 48, 48},
{48, 48, 49, 48, 48},
{48, 48, 48, 49, 49},
}
count := numIslands(input)
fmt.Printf("Islands: %d\n", count)
}
@coxley
Copy link
Author

coxley commented Jul 24, 2022

$ go run main.go
Islands: 3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment