게임 맵의 상태 maps가 매개변수로 주어질 때, 캐릭터가 상대 팀 진영에 도착하기 위해서 지나가야 하는 칸의 개수의 최솟값을 return 하도록 solution 함수를 완성해주세요. 단, 상대 팀 진영에 도착할 수 없을 때는 -1을 return 해주세요.
maps는 n x m 크기의 게임 맵의 상태가 들어있는 2차원 배열로, n과 m은 각각 1 이상 100 이하의 자연수입니다.n과 m은 서로 같을 수도, 다를 수도 있지만, n과 m이 모두 1인 경우는 입력으로 주어지지 않습니다.maps는 0과 1로만 이루어져 있으며, 0은 벽이 있는 자리, 1은 벽이 없는 자리를 나타냅니다.maps = [[1,0,1,1,1],[1,0,1,0,1],[1,0,1,1,1],[1,1,1,0,1],[0,0,0,0,1]]
answer = 11


11개의 칸을 지나서 오는게 최단거리이기에 answer에는 11이 들어간다.
import java.util.*;
class Point{
public int x,y;
Point(int x, int y){
this.x = x;
this.y = y;
}
}
class Solution {
public int BFS(int[][] maps){
Queue<Point> q = new LinkedList<>();
int[][] dis = new int[maps.length][maps[0].length];
int[] dx={-1, 0, 1, 0};
int[] dy={0, 1, 0, -1};
q.offer(new Point(0, 0));
maps[0][0] = 0;
while(!q.isEmpty()){
Point tmp = q.poll();
for(int i=0; i<4; i++){
int nx = tmp.x+dx[i];
int ny = tmp.y+dy[i];
if(nx>=0 && nx<maps.length && ny>=0 && ny<maps[0].length && maps[nx][ny]==1){
maps[nx][ny] = 0;
q.offer(new Point(nx, ny));
dis[nx][ny] = dis[tmp.x][tmp.y]+1;
}
}
}
return dis[maps.length-1][maps[0].length-1];
}
public int solution(int[][] maps) {
Solution t = new Solution();
int answer = t.BFS(maps);
if(answer == 0) return -1;
else return answer+1;
}
}
좌표 (x,y) 관리를 위해 만들어줌
경로 계산을 위해 너비 우선 탐색 방법을 선택함
dis 배열을 사용해 최단 경로를 검색한다.
만약 BFS 함수의 리턴값이 0이란 의미는 최단경로가 없다는 뜻이므로 -1을 리턴해줌.
