[プログラマー]ゲームマップ最短距離(python)


質問リンク-https://programmers.co.kr/learn/courses/30/lessons/1844

私の答え

from collections import deque
def solution(maps):
    
    def bfs(x, y):
        dx = [-1, 1, 0, 0]
        dy = [0, 0, -1, 1]
        
        queue = deque()
        queue.append((x, y))
        
        while queue:
            x, y = queue.popleft()
            
            for i in range(4):
                nx = x + dx[i]
                ny = y + dy[i]
                
                if nx < 0 or nx >=len(maps) or ny < 0 or ny >= len(maps[0]):
                    continue
                if maps[nx][ny] == 0:
                    continue
                    
                if maps[nx][ny] == 1:
                    maps[nx][ny] = maps[x][y] + 1
                    queue.append((nx, ny))
        return maps[len(maps)-1][len(maps[0])-1]
    if bfs(0, 0) == 1:
        return -1
    else:
        return bfs(0, 0)
  • 白準迷宮探索問題
  • に類似する
  • bfsにアクセスするたびに、前の位置値が+1されます.
  • で最後の値を返すと答えは
  • です
  • 最後の値が1の場合、壁に詰まって相手陣営に到達できず、-1
  • に戻る

    他人の解答

    from collections import deque
    
    d = [[1,0], [-1, 0], [0,1], [0,-1]]
    
    def solution(maps):
        r = len(maps)
        c = len(maps[0])
        table = [[-1 for _ in range(c)] for _ in range(r)]
        q = deque()
        q.append([0,0])
        table[0][0] = 1
    
        while q:
            y, x = q.popleft()
    
            for i in range(4):
                ny = y + d[i][0]
                nx = x + d[i][1]
    
                if -1<ny<r and -1<nx<c:
                    if maps[ny][nx] == 1:
                        if table[ny][nx] == -1:
                            table[ny][nx] = table[y][x] + 1
                            q.append([ny, nx])
    
        answer = table[-1][-1]
        return answer