package main import ( "fmt" "math" ) func main() { var w, h int var s string _, _ = fmt.Scan(&w, &h) holes := make(map[int]int) first := -1 for y := 0; y < h; y++ { _, _ = fmt.Scan(&s) for x, c := range []rune(s) { if c == '.' { holes[x+w*y] = 1 if first < 0 { first = x + w*y } } } } // fmt.Println(holes) // 2つの穴に分ける a := make([]int, 0) queue := []int{first} for len(queue) > 0 { // 先頭を取り出してaの洞窟に登録 cell := queue[0] a = append(a, cell) queue = queue[1:] // cellの上下左右を確認して、はじめての空洞ならqueueに追加する up, right, down, left := cell-w, cell+1, cell+w, cell-1 if holes[up] == 1 { if !contains157(a, up) && !contains157(queue, up) { queue = append(queue, up) } } if holes[right] == 1 { if !contains157(a, right) && !contains157(queue, right) { queue = append(queue, right) } } if holes[down] == 1 { if !contains157(a, down) && !contains157(queue, down) { queue = append(queue, down) } } if holes[left] == 1 { if !contains157(a, left) && !contains157(queue, left) { queue = append(queue, left) } } } // fmt.Println(a) // aに含まれなかった空洞がbの洞窟 b := make([]int, 0) for cell := range holes { if !contains157(a, cell) { b = append(b, cell) } } // fmt.Println(b) // aとbの空洞を全パターンでマンハッタン距離を調べて、最短のものを出す ans := math.MaxInt64 for _, cellA := range a { ax, ay := cellA%w, cellA/w for _, cellB := range b { bx, by := cellB%w, cellB/w d := int(math.Abs(float64(ax-bx))) + int(math.Abs(float64(ay-by))) - 1 if ans > d { // fmt.Println("A: ", cellA, ax, ay, ", B: ", cellB, bx, by) ans = d } } } fmt.Println(ans) } func contains157(nums []int, n int) bool { for _, a := range nums { if n == a { return true } } return false }