結果

問題 No.13 囲みたい!
ユーザー warashiwarashi
提出日時 2016-04-29 20:11:33
言語 Go
(1.22.1)
結果
AC  
実行時間 49 ms / 5,000 ms
コード長 1,458 bytes
コンパイル時間 12,159 ms
コンパイル使用メモリ 228,272 KB
実行使用メモリ 5,376 KB
最終ジャッジ日時 2024-04-21 12:26:19
合計ジャッジ時間 13,065 ms
ジャッジサーバーID
(参考情報)
judge3 / judge5
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
5,248 KB
testcase_01 AC 1 ms
5,248 KB
testcase_02 AC 1 ms
5,376 KB
testcase_03 AC 34 ms
5,376 KB
testcase_04 AC 23 ms
5,376 KB
testcase_05 AC 38 ms
5,376 KB
testcase_06 AC 24 ms
5,376 KB
testcase_07 AC 29 ms
5,376 KB
testcase_08 AC 47 ms
5,376 KB
testcase_09 AC 49 ms
5,376 KB
testcase_10 AC 9 ms
5,376 KB
testcase_11 AC 41 ms
5,376 KB
testcase_12 AC 4 ms
5,376 KB
testcase_13 AC 16 ms
5,376 KB
testcase_14 AC 18 ms
5,376 KB
testcase_15 AC 1 ms
5,376 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

package main

import (
	"fmt"
)

type point struct {
	x, y int
}
type node struct {
	d int
	p point
}
type nodeStack []*node

func (s *nodeStack) push(n *node) {
	*s = append(*s, n)
}
func (s *nodeStack) pop() *node {
	n := (*s)[len(*s)-1]
	*s = (*s)[:len(*s)-1]
	return n
}

var went = make(map[point]bool)

func dfs(m [][]int, w, h, x, y int) bool {
	if _, ok := went[point{x: x, y: y}]; ok {
		return false

	}
	r := []point{{0, -1}, {1, 0}, {-1, 0}, {0, 1}}
	c := m[y][x]
	var s nodeStack
	s = append(s, &node{d: -1, p: point{x: x, y: y}})
	for len(s) > 0 {
		n := s.pop()
		if m[n.p.y][n.p.x] == c {
			if _, ok := went[point{x: n.p.x, y: n.p.y}]; ok {
				return true
			}
			went[point{x: n.p.x, y: n.p.y}] = true
			for i, d := range r {
				if i == n.d { // 直前に移動してきた方向には帰らない
					continue
				}
				nx := n.p.x + d.x
				ny := n.p.y + d.y
				if nx < 0 || w <= nx {
					continue
				}
				if ny < 0 || h <= ny {
					continue
				}
				s.push(&node{
					d: 3 - i,
					p: point{
						x: n.p.x + d.x,
						y: n.p.y + d.y,
					},
				})

			}
		}
	}
	return false
}

func main() {
	var w, h int
	fmt.Scan(&w, &h)
	m := make([][]int, h)
	for y := 0; y < h; y++ {
		m[y] = make([]int, w)
		for x := 0; x < w; x++ {
			fmt.Scan(&m[y][x])
		}
	}

	for y := 0; y < h; y++ {
		for x := 0; x < w; x++ {
			if dfs(m, w, h, x, y) {
				fmt.Println("possible")
				return
			}
		}
	}
	fmt.Println("impossible")
	return
}
0