Skip to content

Instantly share code, notes, and snippets.

@tkrs
Created January 5, 2015 17:58
Show Gist options
  • Save tkrs/47acd86ca81df555bf3c to your computer and use it in GitHub Desktop.
Save tkrs/47acd86ca81df555bf3c to your computer and use it in GitHub Desktop.
package main
import (
"bufio"
"fmt"
"os"
"strconv"
)
var Dir [][]int
var M, N int
var MZ [][]int
var ANS int
func init() {
Dir = [][]int{
{0, 1}, // U
{1, 0}, // R
{0, -1}, // D
{-1, 0}, // L
}
}
func scan(ch chan int) {
defer close(ch)
sc := bufio.NewScanner(os.Stdin)
sc.Split(bufio.ScanWords)
for sc.Scan() {
txt := sc.Text()
x, err := strconv.Atoi(txt)
if err != nil {
panic(err.Error())
}
ch <- x
}
if err := sc.Err(); err != nil {
panic("scann error!")
}
}
func read() {
ch := make(chan int)
go scan(ch)
M = <-ch
N = <-ch
MZ = make([][]int, N+1)
for i := 0; i < N; i++ {
MZ[i] = make([]int, M+1)
for j := 0; j < M; j++ {
MZ[i][j] = <-ch
}
}
}
func dfs(y, x int) {
MZ[y][x] = 0
for _, d := range Dir {
dx, dy := x+d[0], y+d[1]
if dx < 0 || dx >= M || dy < 0 || dy >= N {
continue
}
if MZ[dy][dx] == 0 {
continue
}
dfs(dy, dx)
}
}
func p() {
for i := 0; i < N; i++ {
fmt.Println(MZ[i])
}
println()
}
func solve() int {
for i := 0; i < N; i++ {
for j := 0; j < M; j++ {
if MZ[i][j] == 1 {
// p()
dfs(i, j)
ANS++
}
}
}
return 0
}
func answer() {
fmt.Println(ANS)
}
func main() {
read()
solve()
answer()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment