Skip to content

Commit

Permalink
Merge pull request #72 from arunsathiya/solve/200-number-of-islands
Browse files Browse the repository at this point in the history
200. Number Of Islands
  • Loading branch information
arunsathiya committed Feb 25, 2024
2 parents 9cb9a1a + 116560b commit 97ff08e
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/200-number-of-islands/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package main

func dfs(i, j int, grid [][]byte) {
if i > len(grid)-1 || i < 0 || j < 0 || j > len(grid[0])-1 || string(grid[i][j]) != "1" {
return
}
grid[i][j] = '#'
dfs(i+1, j, grid)
dfs(i-1, j, grid)
dfs(i, j+1, grid)
dfs(i, j-1, grid)
}

func numIslands(grid [][]byte) int {
c := 0
for i, row := range grid {
for j, v := range row {
if string(v) == "1" {
c++
dfs(i, j, grid)
}
}
}
return c
}
38 changes: 38 additions & 0 deletions src/200-number-of-islands/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package main

import (
"testing"
)

func TestNumIslands(t *testing.T) {
tests := []struct {
grid [][]byte
expect int
}{
{
grid: [][]byte{
[]byte("11110"),
[]byte("11010"),
[]byte("11000"),
[]byte("00000"),
},
expect: 1,
},
{
grid: [][]byte{
[]byte("11000"),
[]byte("11000"),
[]byte("00100"),
[]byte("00011"),
},
expect: 3,
},
}

for _, test := range tests {
actual := numIslands(test.grid)
if actual != test.expect {
t.Errorf("For grid %v, expected %d islands, but got %d", test.grid, test.expect, actual)
}
}
}

0 comments on commit 97ff08e

Please sign in to comment.