[99클럽 코테 스터디 35일차 TIL] 프로그래머스 - 게임 맵 최단거리
99클럽 코테 스터디 35일차 TIL 입니다.
[level 2] 게임 맵 최단거리 - 1844
구분
문제 설명




maps
answer


풀이 코드
개선하기
Last updated
99클럽 코테 스터디 35일차 TIL 입니다.






Last updated
import java.util.Queue;
import java.util.LinkedList;
class Solution {
private int[] dx = {0, 0, 1, -1};
private int[] dy = {-1, 1, 0, 0};
public int solution(int[][] maps) {
int answer = -1;
int n = maps.length;
int m = maps[0].length;
boolean[][] visited = new boolean[n][m];
Queue<int[]> q = new LinkedList<>();
q.add(new int[]{0, 0, 1});
while (!q.isEmpty()) {
int[] p = q.poll();
int px = p[0];
int py = p[1];
int k = p[2];
if (visited[px][py]) continue;
if (px == n - 1 && py == m - 1) {
return k;
}
visited[px][py] = true;
for (int i = 0; i < 4; i++) {
int x = px + dx[i];
int y = py + dy[i];
if (x >= 0 && y >= 0 && x < n && y < m && !visited[x][y] && maps[x][y] != 0) {
q.add(new int[]{x, y, k + 1});
}
}
}
return answer;
}
}import java.util.Queue;
import java.util.LinkedList;
class Solution {
public int solution(int[][] maps) {
int answer = -1;
int n = maps.length;
int m = maps[0].length;
int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
Queue<int[]> queue = new LinkedList<>();
queue.add(new int[]{0, 0, 1});
while (!queue.isEmpty()) {
int[] peice = queue.poll();
int x = peice[0];
int y = peice[1];
int distance = peice[2];
if (x == n - 1 && y == m - 1) {
return distance;
}
for (int[] dir : directions) {
int dx = x + dir[0];
int dy = y + dir[1];
if (dx >= 0 && dy >= 0 && dx < n && dy < m && maps[dx][dy] != 0) {
queue.add(new int[]{dx, dy, distance + 1});
maps[dx][dy] = 0;
}
}
}
return answer;
}
}