Mini
[bfs] 프로그래머스 경주로 건설 // 비용이 다른 bfs 본문
프로그래머스
SW개발자를 위한 평가, 교육의 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
* 풀이
비용이 다른 그래프를 bfs 로 푸는 방법
vis에 방향정보도 저장해야함, 값 : 그떄의 비용
방문을 안했거나, 방문했어도 (저장된비용 보다 계산한) 비용이 더 싸다면 탐색
목적지에 도달했어도 바로 return X -> 나중도착이 최적일 수있음.
* 코드
import java.util.*;
class Solution {
static class Info{
int y,x,cost,dir;
Info(int y, int x, int cost, int dir){
this.y=y;
this.x=x;
this.cost=cost;
this.dir=dir;
}
public String toString(){
return this.y+" "+this.x+" "+this.cost+" "+this.dir;
}
}
static int[] dy = {1,0,-1,0}; //아래, 오른쪽, 위, 좌
static int[] dx = {0,1,0,-1};
public int solution(int[][] board) {
int answer = Integer.MAX_VALUE;
int n = board.length;
int[][][] vis = new int[n][n][4]; // 방향정보도 추가해야함! (다른방향이면 다른상태임)
var q = new ArrayDeque<Info>();
q.add(new Info(0,0,0,0)); //아래
q.add(new Info(0,0,0,1)); //오른쪽
vis[0][0][0]=0;
vis[0][0][1]=0;
while(q.size()>0){
var cur = q.poll();
int y = cur.y;
int x = cur.x;
int cost = cur.cost;
int dir = cur.dir;
// System.out.println(cur);
// 비용이다른 bfs : 바로 리턴하면 안됨!, 나중도착이 최적해일 수 있음.
if(y==n-1 && x==n-1){
answer = Math.min(answer,cost);
// return cost;
}
for(int i=0;i<4;++i){
int ny=y+dy[i];
int nx=x+dx[i];
if(ny<0 || ny>=n || nx<0 || nx>=n) continue;
if(ny==0 && nx==0) continue; // 시작점
if(board[ny][nx]==1) continue; // 벽
if(Math.abs(i-dir)==2) continue; // 반대방향
int nextCost=0;
if(dir != i){
nextCost = cost + 600; // 직선도로도 만들어야함 -> 100 + 500
}
else{
nextCost = cost + 100;
}
// 이미 방문했어도, 비용이 작다면 재방문 필요!!!
if(vis[ny][nx][i]==0 || vis[ny][nx][i] > nextCost) {
q.add(new Info(ny,nx,nextCost, i));
vis[ny][nx][i]=nextCost;
}
}
}
return answer;
}
}'Algorithm > bfs' 카테고리의 다른 글
| [틀림] 백준 14867 물통 // map bfs (0) | 2025.04.06 |
|---|---|
| [맞음] 백준 1600 말이 되고픈 원숭이 // 3차원 bfs (0) | 2025.04.05 |
| [틀림] 프로그래머스 보물지도 // 3차원 bfs (0) | 2025.04.05 |
| [Algo] 백준 벽부수고 이동하기 c++ // 최단거리는 bfs 3차원 (0) | 2024.09.13 |
| [알고리즘] 리트코드 116. 각 노드의 다음 오른쪽 포인터 채우기 c++ // bfs 트리순회 (0) | 2024.07.01 |