https://school.programmers.co.kr/learn/courses/30/lessons/1844
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
문제 풀이 (JAVA)
import java.util.*;
class Solution {
static int [][] dis; // 위치별 최단거리변수
static boolean [][] visited; // 방문여부
static int [] dx = {-1,1,0,0}; // 탐색할 x좌표
static int [] dy = {0,0,-1,1}; // 탐색할 y좌표
static int N;
static int M;
static int totalCnt=0;
static int [][] arr; // 배열
static int min = Integer.MAX_VALUE;
public int solution(int[][] maps) {
int answer = 0;
N = maps.length;
M = maps[0].length;
arr = maps;
dis = new int[N][M];
visited = new boolean[N][M];
bfs(0,0); // BFS 함수 동작(위치별 최단거리 계산)
if(dis[N-1][M-1] == 0){
answer = -1;
}else{
answer = dis[N-1][M-1]; // 마지막 도착 위치의 최단거리
}
return answer;
}
public static void bfs(int x , int y){
Queue<Point> queue = new LinkedList<>(); // 큐 선언
visited[x][y] = true;
dis[x][y] = 1;
queue.offer(new Point(x,y)); // 좌표 x,y 큐에 입력
// 큐가 없어질때까지 반복
while(!queue.isEmpty()){
Point cur = queue.poll(); // 현재 좌표x,y 추출
for(int i=0; i<dx.length; i++){
int nx = cur.x + dx[i]; // 탐색할 nx좌표
int ny = cur.y + dy[i]; // 탐색할 ny좌표
if(nx>=0 && nx < N && ny>=0 && ny < M && arr[nx][ny]==1 && visited[nx][ny]==false){
visited[nx][ny]=true;
dis[nx][ny]= dis[cur.x][cur.y] +1; // 해당 위치별 최단거리 계산 (이전 거리 + 1)
queue.offer(new Point(nx,ny)); // 큐에 nx,ny 좌표 입력
}
}
}
}
// 좌표를 저장할 x,y 포인트 객체 선언
public static class Point{
int x;
int y;
Point(int x,int y){
this.x=x;
this.y=y;
}
}
}
결론
: 해당 문제는 최단 거리를 구하는 BFS의 기본 공식을 사용하는 문제로 BFS의 개념을 잘 이해하였다면 위와 같은 공식으로 풀 수 있는 문제이다. BFS 기본 공식이 헷갈릴때마다 풀었던 것을 보러 와야겠다...
'프로그래머스(JAVA)' 카테고리의 다른 글
네트워크(인접리스트-DFS) (0) | 2023.04.23 |
---|---|
성격 유형 검사하기 (0) | 2023.01.15 |
체육복 (3) | 2022.07.18 |
K번째 수 (0) | 2022.07.18 |
구명 보트 (0) | 2022.07.16 |