ATC A - 深さ優先探索
https://atcoder.jp/contests/atc001/tasks/dfs_a
提出
WA
code: python
h, w = list(map(int, input().split()))
area = []
for i in range(h):
row = input().split()
area.append(*row)
for x in range(h):
for y in range(w):
if (areaxy == "s"):
s = x, y
if (areaxy == "g"):
g = x, y
moveX = -1, 1, 0, 0
moveY = 0, 0, 1, -1
for i in range(4):
dist = [s0 + moveXi, s1 + moveYi]
解答
code: python
import sys
sys.setrecursionlimit(10**7)
h, w = list(map(int, input().split()))
area = list(input()) for _ in range(h)
searched = [False * w for _ in range(h)]
moveX = 0, 1, 0, -1
moveY = 1, 0, -1, 0
for x in range(h):
for y in range(w):
if (areaxy == "s"):
sx, sy = x, y
if (areaxy == "g"):
gx, gy = x, y
def areaSearch(x, y):
searchedxy = True
# 右, 下、左、上
for i in range(4):
nextX = x + moveXi
nextY = y + moveYi
if (nextX >= 0 and nextX < h and nextY >= 0 and nextY < w):
if (areanextXnextY != '#' and searchednextXnextY == False):
areaSearch(nextX, nextY)
areaSearch(sx, sy)
if (searchedgxgy):
print("Yes")
else:
print("No")
テーマ
#dfs
メモ
再帰関数の呼び出し制限
code: python
import sys
sys.setrecursionlimit(10**7)
提出
checkedの位置、nextX, nextY
code: python
h, w = map(int, input().split())
c = list(input()) for _ in range(h)
for y in range(h):
for x in range(w):
if cyx == "s":
s = y, x
if cyx == "g":
g = y, x
checked = [0 * w for _ in range(h)]
gox = 0, 0, -1, 1
goy = 1, -1, 0, 0
def dfs(nowy, nowx):
for y in goy:
for x in gox:
nextY = nowy + y
nextX = nowx + x
if (nextY < 0 or nextY > h - 1 or nextX < 0 or nextX > w - 1):
pass
elif (checkednextYnextX or cnextYnextX == "#"):
pass
else:
checkednextYnextX = 1
dfs(nextY, nextX)
dfs(s0, s1)
if (checked[g0][g1]):
print("Yes")
else:
print("No")
提出
AC
code: python
h, w = map(int, input().split())
c = list(input()) for _ in range(h)
for i in range(h):
for j in range(w):
if cij == "s":
s = (i, j)
if cij == "g":
g = (i, j)
x = 0,0,1,-1
y = 1,-1,0,0
visited = [False * w for _ in range(h)]
visited[s0][s1] = True
stack = s
while stack:
now_i, now_j = stack.pop(0)
for k in range(4):
next_i, next_j = now_i + xk, now_j + yk
if next_i >= 0 and next_i < h and next_j >= 0 and next_j < w and visitednext_inext_j == False and cnext_inext_j != "#":
visitednext_inext_j = True
stack.append((next_i, next_j))
print("Yes") if visited[g0][g1] else print("No")