Last active
April 21, 2020 09:15
-
-
Save theCoderCat/1e137429345f7223517d60e1bfb4577d to your computer and use it in GitHub Desktop.
This file contains hidden or 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() { | |
slice1 := [][]int{ | |
[]int{1, 1, 1, 6, 6, 6, 6, 5}, | |
[]int{1, 1, 1, 6, 6, 4, 6, 5}, | |
[]int{6, 6, 6, 6, 3, 4, 6, 5}, | |
[]int{6, 2, 2, 6, 3, 3, 5, 5}, | |
} | |
slice2 := [][]int{ | |
[]int{1, 1, 1, 6, 6, 6, 6, 5}, | |
[]int{1, 2, 1, 6, 6, 4, 6, 5}, | |
[]int{6, 6, 6, 6, 3, 4, 6, 5}, | |
[]int{7, 2, 2, 6, 3, 3, 5, 5}, | |
[]int{7, 8, 8, 6, 3, 3, 1, 5}, | |
[]int{7, 8, 9, 6, 3, 3, 1, 5}, | |
} | |
fmt.Println("count map 1") | |
for i := range slice1 { | |
fmt.Println(slice1[i]) | |
} | |
count := countAreas(slice1) | |
fmt.Println("areas:", count) | |
fmt.Println("count map 2") | |
for i := range slice2 { | |
fmt.Println(slice2[i]) | |
} | |
count = countAreas(slice2) | |
fmt.Println("areas:", count) | |
} | |
func countAreas(Map [][]int) int { | |
areas := 0 | |
Y := len(Map) | |
X := len(Map[0]) | |
// fill a check map (same size as map) with false | |
checkMap := make([][]bool, Y) | |
for i := range checkMap { | |
checkMap[i] = make([]bool, X) | |
} | |
for i := 0; i < X; i++ { | |
for j := 0; j < Y; j++ { | |
if !checkMap[j][i] { | |
areas++ | |
lookAround(Map, checkMap, i, j, Map[j][i]) | |
} | |
} | |
} | |
return areas | |
} | |
func lookAround(originMap [][]int, checkMap [][]bool, x int, y int, mark int) bool { | |
Y := len(originMap) | |
X := len(originMap[0]) | |
if x < 0 || x >= X || y < 0 || y >= Y || checkMap[y][x] == true { | |
return false | |
} | |
if originMap[y][x] == mark { | |
// start looking around | |
checkMap[y][x] = true | |
lookAround(originMap, checkMap, x-1, y, mark) | |
lookAround(originMap, checkMap, x+1, y, mark) | |
lookAround(originMap, checkMap, x, y-1, mark) | |
lookAround(originMap, checkMap, x, y+1, mark) | |
return true | |
} | |
return true | |
} | |
func check(e error) { | |
if e != nil { | |
panic(e) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment