[Java] ๋ค์ต์คํธ๋ผ, BFS | ๋ฐฑ์ค 2665 ๋ฏธ๋ก๋ง๋ค๊ธฐ
https://www.acmicpc.net/problem/2665
์ ๊ทผ ๋ฐฉ๋ฒ
์ด ๋ฌธ์ ๋ ๋ค์ต์คํธ๋ผ ์๊ณ ๋ฆฌ์ฆ์ ํ์ฉํ์ฌ ํ ์ ์๋ค. ์ฌ๊ธฐ์๋ ๊ฐ ๋ฐฉ์ ๋ ธ๋๋ก ๋ณด๊ณ , ๊ฒ์ ๋ฐฉ์์ ํฐ ๋ฐฉ์ผ๋ก ๋ณ๊ฒฝํ๋ ์์ ์ ๊ฐ์ค์น๋ก ๊ฐ์ฃผํด ์ต์ ๋ณ๊ฒฝ ํ์ ๊ฒฝ๋ก๋ฅผ ๊ตฌํ๋ค. ์ต๋จ ๊ฒฝ๋ก๊ฐ ์๋ '์ต์ ๋ณ๊ฒฝ ํ์'๋ฅผ ์ฐพ๋๋ค๋ ์ ์ด ์ผ๋ฐ์ ์ธ ๋ค์ต์คํธ๋ผ ์๊ณ ๋ฆฌ์ฆ๊ณผ์ ์ฐจ์ด๋ค.
์์๋ถํฐ ๋๋ฐฉ๊น์ง ๊ฐ๋ ๋์ ๊ฒ์ ๋ฐฉ(0)์ ์ต์๋ก ์ง๋์ผ ํ๋ค.
์ฆ ํฐ ๋ฐฉ(1)์ ์ง๋๊ฐ ๋๋ ๋น์ฉ์ด ๋ฐ์ํ์ง ์๊ณ ๊ฒ์ ๋ฐฉ(0)์ ๊ฑฐ์น ๋๋ ๋น์ฉ์ด 1 ๋งํผ ๋ฐ์ํ๋ค๊ณ ๊ฐ์ฃผํ๊ณ , ์์๋ถํฐ ๋๋ฐฉ๊น์ง BFS๋ฅผ ์งํํ์ฌ ์ต์ ๋น์ฉ์ผ๋ก ๋๋ฐฉ์ ๋์ฐฉํ๋ ๊ฒฝ์ฐ๋ฅผ ๊ตฌํ๋ฉด ๋๋ค.
์ฐ์ ์์ ํ(PriorityQueue)๋ฅผ ์ฌ์ฉํด ํ์ฌ ๋ณ๊ฒฝ ํ์๊ฐ ๊ฐ์ฅ ์ ์ ๊ฒฝ๋ก๋ถํฐ ํ์ํ๋ค. ์ด๋ฅผ ์ํด ์๋์ ๊ฐ์ด ํ์ฌ ๋ ธ๋์ x,y ์ขํ์ ๋ณ๊ฒฝ ํ์๋ฅผ ์์ฑ์ ๊ฐ์ง๋ Point ํด๋์ค๋ฅผ ์ ์ํ๋ค.
static class Point implements Comparable<Point>{
int x, y;
int change;
Point (int x, int y, int change){
this.x = x;
this.y = y;
this.change = change;
}
@Override
public int compareTo(Point other){//change ์์ ๊ฒ ์ฐ์
return Integer.compare(this.change, other.change);
}
}
static int n;
static char[][] maze;
static int[][] visited;
static int[] dx = {-1, 1, 0, 0};
static int[] dy = {0, 0, -1, 1};
visited ๋ฐฐ์ด์ ํด๋น ์ง์ ์ ์ต์ ๋ณ๊ฒฝ ํ์๋ฅผ ์ ์ฅํ๋ค. ์ด๊ธฐ์ visited ๋ฐฐ์ด์ ์ต๋๊ฐ์ผ๋ก ์ค์ ํด์ค๋ค.
์ฐ์ ์์ ํ์ ์์ ์ ์ (new Point(0,0,0))์ ๋ด๊ณ BFS ์งํ
์ํ์ข์ฐ๋ก ์ด๋ํ๋ฉฐ change ๊ฐ ๊ณ์ฐ ํ visited ๋ฐฐ์ด์ ์ ๋ฐ์ดํธ ํด์ค๋ค.
- '1'์ธ ์นธ์ผ๋ก ์ด๋ํ ๋๋ ๋น์ฉ์ด ๋ค์ง ์์ (change + 0)
- '0'์ธ ์นธ์ผ๋ก ์ด๋ํ ๋๋ ๋น์ฉ์ด 1 ์ฆ๊ฐ (change + 1)
๋ค์์ผ๋ก change ๊ฐ์ด ์ ์ ์ ์ ์ผ๋ก ์ ๊ณผ์ ์ ๋ ์ง์ ๋๋ฌ์ ๊น์ง ๋ฐ๋ณตํ๋ค.
private static int solution() {
visited = new int[n][n];
for(int i=0; i<n; i++){
Arrays.fill(visited[i], Integer.MAX_VALUE);
}
PriorityQueue<Point> q = new PriorityQueue<>();
q.offer(new Point(0,0,0));
while(!q.isEmpty()){
Point current = q.poll();
int x = current.x;
int y = current.y;
if(x== n-1 && y == n-1){
return current.change;
}
for(int i=0; i<4; i++){
int nextX = x + dx[i];
int nextY = y + dy[i];
if(nextX < 0 || nextX > n-1 || nextY < 0 || nextY > n-1) continue;
int change = current.change + (maze[nextX][nextY] == '1' ? 0 : 1);
if(change < visited[nextX][nextY]){
visited[nextX][nextY] = change;
q.offer(new Point(nextX, nextY, change));
}
}
}
return -1;
}
๋ฐฐ์ด์ :
์ต๋จ ๊ฒฝ๋ก๋ฅผ ์ฐพ์๊ฐ๋ ๋ค์ต์คํธ๋ผ ์๊ณ ๋ฆฌ์ฆ์ด ๋ค์ํ ๋ฌธ์ ์ ์์ฉ๋ ์ ์์์ ์๊ฒ ๋์๋ค. ํนํ ์ด ๋ฌธ์ ๋ ๊ทธ๋ํ์ ๊ฐ์ค์น๋ฅผ ๊ฒฝ๋ก๊ฐ ์๋ ์๋ก์ด ๊ธฐ์ค(๋ณ๊ฒฝ ํ์)์ผ๋ก ์ค์ ํ๋ ๊ฒ์ด ํ์ด์ ํต์ฌ์ด์๋ ๊ฒ ๊ฐ๋ค.