package main import ( "bufio" "fmt" "os" "strconv" ) func configure(scanner *bufio.Scanner) { scanner.Split(bufio.ScanWords) scanner.Buffer(make([]byte, 1000005), 1000005) } func getNextString(scanner *bufio.Scanner) string { scanned := scanner.Scan() if !scanned { panic("scan failed") } return scanner.Text() } func getNextInt(scanner *bufio.Scanner) int { i, _ := strconv.Atoi(getNextString(scanner)) return i } func getNextInt64(scanner *bufio.Scanner) int64 { i, _ := strconv.ParseInt(getNextString(scanner), 10, 64) return i } func getNextFloat64(scanner *bufio.Scanner) float64 { i, _ := strconv.ParseFloat(getNextString(scanner), 64) return i } func main() { fp := os.Stdin wfp := os.Stdout extra := 0 if os.Getenv("I") == "IronMan" { fp, _ = os.Open(os.Getenv("END_GAME")) extra = 100 } scanner := bufio.NewScanner(fp) configure(scanner) writer := bufio.NewWriter(wfp) defer func() { r := recover() if r != nil { fmt.Fprintln(writer, r) } writer.Flush() }() solve(scanner, writer) for i := 0; i < extra; i++ { fmt.Fprintln(writer, "-----------------------------------") solve(scanner, writer) } } func solve(scanner *bufio.Scanner, writer *bufio.Writer) { h := getNextInt(scanner) w := getNextInt(scanner) aa := make([]int, h*w) uf := make([]int, h*w) for i := 0; i < h*w; i++ { aa[i] = getNextInt(scanner) uf[i] = i } for i := 0; i < h*w; i++ { if i-1 >= 0 && i%w != 0 && aa[i] == 1 && aa[i-1] == 1 { uf[root(i, uf)] = root(i-1, uf) } if i-w >= 0 && aa[i] == 1 && aa[i-w] == 1 { uf[root(i, uf)] = root(i-w, uf) } } m := map[int]int{} for i := 0; i < h*w; i++ { if aa[i] == 0 { continue } m[root(i, uf)]++ } fmt.Fprintln(writer, len(m)) } func root(i int, uf []int) int { if i == uf[i] { return i } uf[i] = root(uf[i], uf) return uf[i] }