Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| 8 | 9 | 10 | 11 | 12 | 13 | 14 |
| 15 | 16 | 17 | 18 | 19 | 20 | 21 |
| 22 | 23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 문자형 배열
- 값/참조/주소에 의한 전달
- 프로그래머스 배열만들기4
- 범위 기반 for문
- 알고리즘 조건
- c언어 괄호검사
- IPv4 주소체계
- 유형 변환
- 백준 파이썬
- 원형 연결 구조 연결된 큐
- C언어 덱
- 운영체제 기능
- auto 키워드
- C언어 계산기 프로그램
- l-value참조자
- 입출력 관리자
- string유형
- 주기억장치
- C언어 스택 연산
- 괄호 검사 프로그램
- const화
- LAN의 분류
- 회전 및 자리 이동 연산
- const l-value참조자
- r-value참조자
- 문제해결 단계
- getline()함수
- 네트워크 결합
- 프로그래머스 푸드 파이트 대회
- 논리 연산
Archives
- Today
- Total
chyam
[백준] 14940번,python - 쉬운 최단거리 본문

https://www.acmicpc.net/problem/14940
from collections import deque
import sys
input = sys.stdin.readline
n, m = map(int,input().split())
li = []
des_x, des_y = -1,-1
direct = [[1,0],[-1,0],[0,1],[0,-1]]
for i in range(n):
tmp = list(map(int,input().split()))
for j in range(m):
if tmp[j] == 2: # 목표지점 위치 저장
des_x, des_y = i, j
li.append(tmp)
# 거리 기록 배열 (-1로 초기화)
dist = [[-1]*m for _ in range(n)]
def bfs(sx,sy):
queue = deque([(sx,sy)])
dist[sx][sy] = 0
while queue:
x, y = queue.popleft()
for dx, dy in direct:
nx, ny = x + dx, y + dy
if 0 <= nx < n and 0 <= ny < m:
if li[nx][ny] != 0 and dist[nx][ny] == -1: # 아직 접근 안한곳이고 접근가능한곳
dist[nx][ny] = dist[x][y] + 1 # 원래꺼에서 1칸 옮긴거니까 1더해줌
queue.append((nx,ny))
bfs(des_x, des_y)
for i in range(n):
for j in range(m):
if li[i][j] == 0:
print(0, end=" ")
else:
print(dist[i][j], end=" ")
print()
# 처음 풀이. bfs로 다 접근해서 시간초과뜸
from collections import deque
import sys
input = sys.stdin.readline
n, m = map(int,input().split())
li = []
des_x, des_y = 0,0
direct = [[1,0],[-1,0],[0,1],[0,-1]]
for i in range(n):
tmp = list(map(int,input().split()))
for j in range(m):
if tmp[j] == 2:
des_x, des_y = i, j
li.append(tmp)
def bfs(li,i,j):
visited = [[False]*m for _ in range(n)]
queue = deque([(i,j,0)])
visited[i][j] = True
while queue:
x, y, cnt = queue.popleft()
if x == des_x and y == des_y:
return cnt
for dx, dy in direct:
nx, ny = x + dx, y + dy
if 0 <= nx < n and 0 <= ny < m and not visited[nx][ny] and li[nx][ny] != 0:
queue.append((nx,ny,cnt+1)) # 접근 가능한 곳이면 접근 후 방문 기록
visited[nx][ny] = True
return -1
for i in range(n):
for j in range(m):
if li[i][j] == 0:
print(0 , end =" ")
else:
print(bfs(li,i,j), end = " ")
print()'백준' 카테고리의 다른 글
| [백준] 5430번,python - AC (0) | 2025.09.25 |
|---|---|
| [백준] 1976번,python - 여행 가자 (0) | 2025.09.24 |
| [백준] 2178번, python - 미로 탐색 (0) | 2025.09.22 |
| [백준] 2559번,python - 수열 (0) | 2025.09.19 |
| [백준] 11000번,python - 강의실 배정 (0) | 2025.09.18 |