반응형
풀이
최단 경로를 구하는 문제입니다. bfs를 이용해서 풀었습니다.
queue를 이용해 뽑아온 x,y 값과 + dx,dy를 더해서 다음 노드의 위치를 알아냅니다.
다음 노드의 값이 1일 경우 graph[x][y] 노드의 값에 + 1한 최단 거리 값을 graph[nx}[ny] 노드에 기록 해줍니다.
해당 노드로 이동하기 위해서 queue에 nx, ny의 값을 넣고 위의 과정을 queue가 빌때 까지 반복합니다.
자바
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
class Node {
private int x;
private int y;
public Node(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
}
public class Main {
private static int n, m;
private static int[][] graph = new int[101][101];
private static int dx[] = {-1, 1, 0, 0};
private static int dy[] = {0, 0, -1, 1};
private static int bfs(int x, int y) {
Queue<Node> q = new LinkedList<>();
q.offer(new Node(x, y));
while (!q.isEmpty()) {
Node node = q.poll();
x = node.getX();
y = node.getY();
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx < 0 || nx >= n || ny < 0 || ny >= m) continue;
if (graph[nx][ny] == 0) continue;
if (graph[nx][ny] == 1) {
graph[nx][ny] = graph[x][y] + 1;
q.offer(new Node(nx, ny));
}
}
}
return graph[n - 1][m - 1];
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
for (int i = 0; i < n; i++) {
String str = br.readLine();
for (int j = 0; j < m; j++) {
graph[i][j] = str.charAt(j) - '0';
}
}
System.out.println(bfs(0, 0));
}
}
파이썬
from collections import deque
from sys import stdin
n, m = map(int, input().split())
graph = [list(map(int, stdin.readline().rstrip())) for _ in range(n)]
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
def bfs(x, y):
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 >= n or ny < 0 or ny >= m:
continue
if graph[nx][ny] == 0:
continue
if graph[nx][ny] == 1:
graph[nx][ny] = graph[x][y] + 1
queue.append((nx, ny))
return graph[n - 1][m - 1]
print(bfs(0, 0))
'백준' 카테고리의 다른 글
10989번: 수 정렬하기 3 (0) | 2022.02.26 |
---|---|
2751번: 수 정렬하기 2 (0) | 2022.02.26 |
2667번: 단지번호붙이기 (0) | 2022.02.24 |
2553번: 마지막 팩토리얼 수 (0) | 2022.02.21 |
11000번: 강의실 배정 (0) | 2022.02.20 |