[BOJ 2206] ๋ฒฝ๋ถ์๊ณ ์ด๋ํ๊ธฐ
1. ๋ฌธ์ : https://www.acmicpc.net/problem/2206
2. ํ์ด
๋ฒฝ์ ๋ถ์๊ณ ๊ฐ๋ ๊ฒฝ์ฐ์ ๋ถ์์ง ์๋ ๊ฒฝ์ฐ๋ฅผ ๊ตฌ๋ถํ๊ธฐ ์ํด visited[][][] 3์ฐจ์๋ฐฐ์ด๋ก ๊ตฌ์ฑ
3. ์ฝ๋
package baekjoon;
import java.util.*;
public class ๋ฒฝ๋ถ์๊ณ ์ด๋ํ๊ธฐ {
static int[] dx = { 1, 0, -1, 0 };
static int[] dy = { 0, 1, 0, -1 };
static int n, m;
static int[][] board;
static boolean[][][] visited;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
m = scanner.nextInt();
scanner.nextLine();
board = new int[n][m];
for (int i = 0; i < n ; i++) {
String str = scanner.nextLine();
for (int j = 0; j < m; j++) {
board[i][j] = Integer.valueOf(str.charAt(j)) - '0';
}
}
visited = new boolean[n][m][2];
System.out.println(bfs(0, 0));
}
private static int bfs(int x, int y) {
Queue<Node> q = new LinkedList<>();
q.add(new Node(x, y, 1, 0));
visited[x][y][0] = true; //0์ ๋ฒฝ์ ๋ถ์์ง ์๊ณ ๋ฐฉ๋ฌธํ ๋
ธ๋์ ๋ฐฉ๋ฌธ ์ฌ๋ถ
visited[x][y][1] = true; //1์ ๋ฒฝ์ ๋ถ์๋ฉด์ ๋ฐฉ๋ฌธํ ๋
ธ๋์ ๋ฐฉ๋ฌธ ์ฌ๋ถ
while (!q.isEmpty()) {
Node current = q.poll();
if (current.x == n - 1 && current.y == m - 1) return current.count;
for (int i = 0; i < 4; i++) {
int nx = current.x + dx[i];
int ny = current.y + dy[i];
if (nx >= 0 && nx < n && ny >= 0 && ny < m) {
if(board[nx][ny] == 0) { //๋ฒฝ์ด ์๋ ๋
if (visited[nx][ny][current.wall] == false) { //ํ์ฌ๊น์ง ์จ ๋ฐฉ๋ฒ(๋ฒฝ์ ๋ถ์๋์ง ์๋์ง)์ผ๋ก ๋ฐฉ๋ฌธํ ์ ์ด ์๋ค๋ฉด ๋ฐฉ๋ฌธํ๋ค.
q.add(new Node(nx, ny, current.count + 1, current.wall));
visited[nx][ny][current.wall] = true;
}
}
else if (board[nx][ny] == 1) { //๋ฒฝ์ผ๋
if (current.wall == 0 && visited[nx][ny][1] == false) { //ํ์ฌ๊น์ง ๋ฒฝ์ ๋ถ์์ ์ด ์๊ณ , ๋ฒฝ์ ๋ถ์ด์ ๋ฐฉ๋ฌธํ ์ ์ด ์๋ค๋ฉด ๋ฐฉ๋ฌธํ๋ค.
q.add(new Node(nx, ny, current.count + 1, 1));
visited[nx][ny][1] = true;
}
}
}
}
}
return -1;
}
private static class Node {
private int x;
private int y;
private int count;
private int wall; //๋ฒฝ์ ๋ถ์๋ฉด์ ์๋์ง ์๋์ง. 0์ด๋ฉด ์๋๊ณ 1์ด๋ฉด ๋ฒฝ์ ๋ถ์๋ฉด์ ์๋ค๋ ๊ฒ์ ์๋ฏธํ๋ค.
public Node(int x, int y, int count, int wall) {
this.x = x;
this.y = y;
this.count = count;
this.wall = wall;
}
}
}
'๐ป Coding Problems Solving > DFS | BFS | Backtracking' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[BOJ 5427] ํ์ถ (0) | 2023.08.27 |
---|---|
[BOJ 5427] ๋ถ (0) | 2023.08.24 |
[BOJ 16234] ์ธ๊ตฌ์ด๋ (0) | 2023.08.17 |
[BOJ 1103] ์คํํธ๋งํฌ (0) | 2023.08.11 |
[BOJ 9466] ํ ํ๋ก์ ํธ (0) | 2023.08.01 |
์ต๊ทผ๋๊ธ