programmers_게임 맵 최단거리_java
2023. 4. 11. 20:45ㆍAlgorithm/Programmers
728x90
https://school.programmers.co.kr/learn/courses/30/lessons/1844
import java.util.*;
class Solution {
private static int[][] delta = {{0,1}, {0, -1}, {1, 0}, {-1,0}};
public int solution(int[][] maps) {
int answer = 0;
answer = bfs(maps, maps[0].length, maps.length);
return answer;
}
public int bfs(int[][] maps, int width, int height){
int cnt = 0;
Queue<Point> queue = new LinkedList<>();
boolean[][] visited = new boolean[height+1][width+1];
queue.offer(new Point(1,1));
while(!queue.isEmpty()){
int size = queue.size();
cnt++; // 이동 횟수
for(int i = 0; i<size; i++){
Point now = queue.poll();
if(visited[now.y][now.x]) continue;
visited[now.y][now.x] = true;
if(now.y == height && now.x == width){ // 목적지 도착
return cnt;
}
for(int j = 0; j<4; j++){
int nexty = now.y + delta[j][0];
int nextx = now.x + delta[j][1];
if(0<nexty && nexty<=height && 0<nextx && nextx<=width && maps[nexty-1][nextx-1] == 1 && !visited[nexty][nextx]){
queue.offer(new Point(nexty, nextx));
}
}
}
}
return -1;
}
public class Point{
int y, x;
public Point(int y, int x){
this.y = y;
this.x = x;
}
}
}
'Algorithm > Programmers' 카테고리의 다른 글
programmers_2개 이하로 다른 비트_java (0) | 2023.04.13 |
---|---|
programmers_[1차] 프렌즈4블록_java (0) | 2023.04.13 |
programmers_[3차] 파일명 정렬_java (0) | 2023.04.11 |
programmers_모음 사전_java (0) | 2023.04.11 |
programmers_방문 길이_java (0) | 2023.04.11 |