結果
| 問題 |
No.157 2つの空洞
|
| コンテスト | |
| ユーザー |
tsuchinaga
|
| 提出日時 | 2019-04-23 08:57:45 |
| 言語 | Go (1.23.4) |
| 結果 |
AC
|
| 実行時間 | 2 ms / 2,000 ms |
| コード長 | 1,957 bytes |
| コンパイル時間 | 10,698 ms |
| コンパイル使用メモリ | 229,096 KB |
| 実行使用メモリ | 6,820 KB |
| 最終ジャッジ日時 | 2024-10-13 04:34:23 |
| 合計ジャッジ時間 | 11,446 ms |
|
ジャッジサーバーID (参考情報) |
judge3 / judge2 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 4 |
| other | AC * 16 |
ソースコード
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
}
tsuchinaga