☑️ 문제: 게임 맵 최단거리
https://school.programmers.co.kr/learn/courses/30/lessons/1844
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
☑️ Code: BFS 풀이
import java.util.*;
class Solution {
public int solution(int[][] maps) {
// 0. init data
int n = maps.length;
int m = maps[0].length;
Queue<Integer> queue = new LinkedList<>();
int[][] dist = new int[n][m];
// 1. push first point
int x = 0, y = 0;
queue.offer(x);
queue.offer(y);
dist[y][x] = 1;
// 2. bfs
int answer = -1;
int nx, ny;
int[] dx = { 0, 0, 1, -1 };
int[] dy = { 1, -1, 0, 0 };
while (!queue.isEmpty()) {
x = queue.poll();
y = queue.poll();
if (x == m - 1 && y == n - 1) {
answer = dist[y][x];
break;
}
for (int i = 0; i < 4; i++) {
nx = x + dx[i];
ny = y + dy[i];
if (!isOutBound(nx, ny, n, m) && maps[ny][nx] == 1 && dist[ny][nx] == 0) {
queue.offer(nx);
queue.offer(ny);
dist[ny][nx] = dist[y][x] + 1;
}
}
}
return answer;
}
boolean isOutBound(int x, int y, int n, int m) {
return y < 0 || y >= n || x < 0 || x >= m;
}
}
'TIL (Today I Learned)' 카테고리의 다른 글
99클럽 코테 스터디 37일차 TIL + 오늘의 학습 키워드 (0) | 2024.08.28 |
---|---|
99클럽 코테 스터디 36일차 TIL + 오늘의 학습 키워드 (0) | 2024.08.27 |
99클럽 코테 스터디 34일차 TIL + 오늘의 학습 키워드 (0) | 2024.08.24 |
99클럽 코테 스터디 33일차 TIL + 오늘의 학습 키워드 (0) | 2024.08.24 |
99클럽 코테 스터디 32일차 TIL + 오늘의 학습 키워드 (0) | 2024.08.23 |