Algorithm/acmicpc.net

파이썬 리스트의 원소를 한번에 출력하고 싶다면 (#14940)

winney916 2024. 7. 2. 09:43
728x90

#14940 쉬운 최단거리 (https://www.acmicpc.net/problem/14940)

 

 

자꾸 이것저것 조건 빼먹어서 은근히 귀찮았던 문제였다.

 

단순 BFS로 풀이했다.

다만 시작 지점이 입력마다 달라질 수 있음을 유의해야하며

벽에 가로막혀 도달할 수 없는 지점은 -1로 표기하는 것이 주의해야할 지점이다.

 

h, w = map(int, input().split())

maps = []

t = []
# points = []

for r in range(h):
    tmp = list(map(int, input().split()))
    for c in range(w):
        if tmp[c] == 2:  # target check
            t.append([r, c])
            tmp[c] = 0  # change target value = 0 (결과값을 만들기 위한 세팅)
        elif tmp[c] == 1:
            # 원래 갈 수 있는 땅인 부분 중에서 도달할 수 없는 위치는 -1을 출력한다.
            tmp[c] = -1
    maps.append(tmp)

# 각 points에서 target을 향하는 최단거리는, target에서 각 points로 향하는 최단거리와 같다.
# 즉, target에서 모든 points로 향하는 거리를 작성하면 된다.

# for m in maps:
#     print(m)

moves = [[1, 0], [-1, 0], [0, 1], [0, -1]]  # up, down, right, left

# target을 bfs를 위한 que로 쓰면 되겠다.


def is_valid_pos(y, x):
    return (0 <= y < h) and (0 <= x < w) and (maps[y][x] == -1)  # is not 0


vistied = [[False for _ in range(w)] for __ in range(h)]
vistied[t[0][0]][t[0][1]] = True
while t:
    y, x = t.pop(0)
    cost = maps[y][x]
    for my, mx in moves:
        ny, nx = y + my, x + mx
        if is_valid_pos(ny, nx) and not vistied[ny][nx]:
            maps[ny][nx] = cost + 1
            t.append([ny, nx])
            vistied[ny][nx] = True

# print("after bfs")
for m in maps:
    print(*m)

 

 

원래는, 숫자로 된 리스트를 하나의 공백 간격으로 출력하고 싶을 때 다음과 같이 작성했었다.

 

print(" ".join(list(map(str, m)))

 

join함수는 string 타입만 받을 수 있다보니 이렇게 했었는데, 더욱 간편한 방법이 있었다.

 

print(*m)

 

파이썬 짱!