結果

問題 No.157 2つの空洞
ユーザー tsuchinagatsuchinaga
提出日時 2019-04-23 08:57:45
言語 Go
(1.22.1)
結果
AC  
実行時間 3 ms / 2,000 ms
コード長 1,957 bytes
コンパイル時間 13,832 ms
コンパイル使用メモリ 246,708 KB
実行使用メモリ 6,944 KB
最終ジャッジ日時 2024-04-21 06:00:32
合計ジャッジ時間 13,019 ms
ジャッジサーバーID
(参考情報)
judge2 / judge1
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
6,812 KB
testcase_01 AC 2 ms
6,812 KB
testcase_02 AC 2 ms
6,944 KB
testcase_03 AC 2 ms
6,940 KB
testcase_04 AC 2 ms
6,940 KB
testcase_05 AC 2 ms
6,940 KB
testcase_06 AC 2 ms
6,940 KB
testcase_07 AC 2 ms
6,940 KB
testcase_08 AC 2 ms
6,944 KB
testcase_09 AC 2 ms
6,940 KB
testcase_10 AC 2 ms
6,940 KB
testcase_11 AC 2 ms
6,944 KB
testcase_12 AC 3 ms
6,944 KB
testcase_13 AC 2 ms
6,940 KB
testcase_14 AC 2 ms
6,940 KB
testcase_15 AC 2 ms
6,944 KB
testcase_16 AC 2 ms
6,944 KB
testcase_17 AC 3 ms
6,940 KB
testcase_18 AC 3 ms
6,944 KB
testcase_19 AC 3 ms
6,944 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

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
}
0