from collections import deque def check(order): field = [[1 for _ in range(W)] for _ in range(H)] for o in order: i, j = o field[i][j] = 0 global si, sj global gi, gj deq = deque() deq.append((si, sj)) dist = [[INF for _ in range(W)] for _ in range(H)] dist[si][sj] = 0 while deq: i, j = deq.popleft() for di, dj in dir: ni = i+di nj = j+dj if 0<=nidist[i][j]+1: dist[ni][nj] = dist[i][j]+1 deq.append((ni, nj)) if len(order)-1==dist[gi][gj]: return True else: return False def dfs(i, j, order): global gi, gj if i==gi and j==gj: if check(order): ans.add(tuple(order)) return for di, dj in dir: ni = i+di nj = j+dj if 0<=ni