0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

pythonでコーディング問題を解く4

Posted at

https://qiita.com/tosei/items/4bfe7345a7a78abc572c
続き

問題

こちらの問題を解いてみた
C - 幅優先探索
https://atcoder.jp/contests/abc007/tasks/abc007_3

from collections import deque
import numpy

Row, Column = map(int, input().split())
startY, startX = map(int, input().split())
goalY, goalX = map(int, input().split())

# 位置と配列上の添字はずれているのでここで調整する
startY, startX = startY - 1, startX - 1
goalY, goalX = goalY - 1, goalX - 1

maps = []
distances = []

# マップデータと距離データを初期化する
for i in range(Row) :
    # 一文字ずつ配列にする
    maps.append(list(input()))
    # カラム数分-1で埋める
    distances.append(numpy.full(Column, -1))

def bfs(startY, startX) :
    # 初期設定
    queue = deque([])
    # 起点をキューにpushする
    queue.append((startY, startX))
    distances[startY][startX] = 0
    
    nextPos = [(1,0),(0,-1),(-1,0),(0,1)]
    
    while len(queue) > 0:
        # キューの一番前を取得する
        currentY, currentX = queue.popleft()

        # 隣接する点を調べ、未訪問の通路の距離を更新し、キューに追加する        
        for y, x in nextPos:
            nextY, nextX = currentY + y, currentX + x

            if distances[nextY][nextX] == -1 and maps[nextY][nextX] == '.' :
                distances[nextY][nextX] = distances[currentY][currentX] + 1
                queue.append((nextY, nextX))
    
    # reutrn maps,distances
    return distances[goalY][goalX]

print(bfs(startY, startX))
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?