참고
문제해설
문제 로직고민
NOTE
•
거리가 1로 고정된 최단거리 == BFS (너무 유명해서 설명할게 없음)
작성코드
NOTE
import java.util.*;
class Solution {
int[] dir_y = {-1,0,1,0};
int[] dir_x = {0,1,0,-1};
public int solution(int[][] maps) {
int y = maps.length;
int x = maps[0].length;
Queue<int[]> queue = new LinkedList();
boolean[][] visited = new boolean[y][x];
queue.offer(new int[]{0,0,1});
visited[0][0] = true;
int result = Integer.MAX_VALUE;
while(!queue.isEmpty()){
int[] cur = queue.poll();
int move = cur[2];
if(cur[0] == y-1 && cur[1] == x-1){
result = Math.min(result, move);
continue;
}
for(int i=0; i<4; i++){
int my = cur[0] + dir_y[i];
int mx = cur[1] + dir_x[i];
if(my < 0 || my >= y || mx < 0 || mx >= x) continue;
if(!visited[my][mx] && maps[my][mx] == 1){
visited[my][mx] = true;
queue.offer(new int[]{my, mx, move+1});
}
}
}
return result == Integer.MAX_VALUE ? -1 : result;
}
}
Java
복사
다른사람 풀이
NOTE
import java.util.*;
class Solution {
public int solution(int[][] maps) {
int rows = maps.length;
int cols = maps[0].length;
int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; // 상하좌우
Queue<int[]> queue = new LinkedList<>();
queue.offer(new int[]{0, 0, 1}); // 시작 위치와 거리
while (!queue.isEmpty()) {
int[] current = queue.poll();
int row = current[0];
int col = current[1];
int distance = current[2];
if (row == rows - 1 && col == cols - 1) {
return distance; // 목적지에 도달한 경우 최단거리 반환
}
for (int[] dir : directions) {
int newRow = row + dir[0];
int newCol = col + dir[1];
if (newRow >= 0 && newRow < rows && newCol >= 0 && newCol < cols && maps[newRow][newCol] == 1) {
maps[newRow][newCol] = 0; // 방문한 위치는 재방문하지 않도록 표시
queue.offer(new int[]{newRow, newCol, distance + 1});
}
}
}
return -1; // 목적지에 도달하지 못한 경우
}
}
Java
복사
더 깔끔한 코드
•
내가 작성한 코드는 최단거리에 도달하고, 이후의 값까지 계산하고 있다.
•
특수한 상황이 아니면 위처럼 바로 반환하는게 더 효율적