๋ฌธ์
https://www.acmicpc.net/problem/3055
3055๋ฒ: ํ์ถ
์ฌ์ ํ ์ํ์ ๊ตฐ์ฃผ ์ด๋ฏผํ์ ๋๋์ด ๋ง๋ฒ ๊ตฌ์ฌ์ ์์ ๋ฃ์๊ณ , ๊ทธ ๋ฅ๋ ฅ์ ์คํํด๋ณด๊ธฐ ์ํด ๊ทผ์ฒ์ ํฐ๋ฑ์ฒ์ ํ์๋ฅผ ์ผ์ผํค๋ ค๊ณ ํ๋ค. ์ด ์ฒ์๋ ๊ณ ์ด๋์น๊ฐ ํ ๋ง๋ฆฌ ์ด๊ณ ์๋ค. ๊ณ ์ด๋์น๋ ์
www.acmicpc.net
๋ด ๋ฌธ์ ํ์ด
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.StringTokenizer;
public class BOJ_3055 {
static int r, c;
static char[][] map;
static int[] start;
static Deque<int[]> que = new ArrayDeque<>();
static int[] dx = {0, 0, -1, 1};
static int[] dy = {-1, 1, 0, 0};
public static int bfs() {
while(!que.isEmpty()) {
int[] now = que.removeFirst();
int x = now[0];
int y = now[1];
int check = now[2]; // ๋ฌผ์ธ์ง ๊ณ ์ด๋์น์ธ์ง ํ๋จ (๋ฌผ == 0, ๊ณ ์ด๋์น == 1)
int cnt = now[3];
for(int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if(nx < 0 || ny < 0 || nx >= r || ny >= c) continue;
if(check == 1 && map[nx][ny] == 'D') {
return cnt+1;
}
if(map[nx][ny] != '.') continue;
if(check == 0) map[nx][ny] = '*';
if(check == 1) map[nx][ny] = 'S';
que.add(new int[]{nx, ny, check, cnt+1});
}
}
return -1;
}
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
st = new StringTokenizer(in.readLine());
r = Integer.parseInt(st.nextToken());
c = Integer.parseInt(st.nextToken());
map = new char[r][c];
for(int i = 0; i < r; i++) {
String str = in.readLine();
for(int j = 0; j < c; j++) {
map[i][j] = str.charAt(j);
if(map[i][j] == '*') que.add(new int[]{i, j, 0, 0}); // ๋ฌผ์ ์์น ํ์ ์ถ๊ฐ
else if(map[i][j] == 'S') start = new int[]{i, j, 1, 0}; // ๊ณ ์ด๋์น ์์น ์ผ๋จ ์ ์ฅ
}
}
que.add(start); // ๊ณ ์ด๋์น๋ฅผ ๋ฌผ ์ด๋ ํ ์์ง์ด๊ธฐ ์ํด ๋ง์ง๋ง์ ์ถ๊ฐ
int ans = bfs();
System.out.println(ans == -1 ? "KAKTUS" : ans);
}
}
๐ BFS ๋ฌธ์
- ์ฃผ์ด์ง๋ ์ง๋์ ์ ๋ณด๋ฅผ ๋ฐ์ผ๋ฉด์, ๋ฌผ์ด๋ ๊ณ ์ด๋์น๊ฐ ์
๋ ฅ๋ ๊ฒฝ์ฐ๋ฅผ ์กฐ๊ฑด์ฒ๋ฆฌํ๋ค.
๊ณ ์ด๋์น๋ ๋ฌผ์ด ์ฐฐ ์์ ์ธ ์นธ์ผ๋ก ์ด๋ํ ์ ์์ผ๋ฏ๋ก, ๋ฌผ ๋จผ์ ์ด๋ ํ ๊ณ ์ด๋์น๋ฅผ ์ด๋์ํค๊ณ ์
๋ฌผ์ด ์ ๋ ฅ๋ ๊ฒฝ์ฐ ๋ฐ๋ก que์ ์ถ๊ฐํด์ฃผ์๊ณ , ๊ณ ์ด๋์น๋ start ๋ณ์์ ์ ์ฅ ํ ๋ง์ง๋ง์ ์ถ๊ฐํ๋ค.
์ด ๋, ๋ฌผ์ ๊ฒฝ์ฐ que์ ์ถ๊ฐํ๋ int ๋ฐฐ์ด์ ์ธ ๋ฒ์งธ ์์๋ฅผ 0์ผ๋ก, ๊ณ ์ด๋์น๋ 1๋ก ๋ง๋ค์ด์ ์ถ๊ฐํ๋ค. - bfs ๋ฉ์๋์์๋ ์ฒซ ๋ฒ์งธ ์์๋ถํฐ ๊บผ๋ด์ด ํ์ํ๋๋ฐ,
๊ณ ์ด๋์น์ด๋ฉด์, ์์ผ๋ก ํ์ํ๋ ค๋ ์๋ฆฌ๊ฐ 'D'์ผ ๊ฒฝ์ฐ ํ์ถ์ ์ฑ๊ณตํ ๊ฒ์ผ๋ก ํ๋จํด์ฃผ์๋ค.
๊ทธ๋ฆฌ๊ณ ์์ผ๋ก ํ์ํ๋ ค๋ ์๋ฆฌ๊ฐ '.'์ด ์๋๋ผ๋ฉด ๊ทธ ์๋ฆฌ๋ก๋ ๊ฐ ์ ์์ผ๋ฏ๋ก continue ํ๋ค. - ๋ฐ์ ๊ฐ๋ฅํ ์์ธ๋ฅผ ๋ชจ๋ ํจ์คํ๋ค๋ฉด ์์ผ๋ก ํ์ํ๋ ค๋ ์๋ฆฌ์ ๋ฌผ, ํน์ ๊ณ ์ด๋์น๋ฅผ ํ์ฐ์์ผ์ฃผ์๋ค.
๊ทธ๋ฆฌ๊ณ que์ ํด๋นํ๋ ์๋ฆฌ๋ฅผ ์๋ก์ด ์์์ ์ผ๋ก ์ถ๊ฐํ๋ค.
๐ก ํผ๋๋ฐฑ
- https://seolhee2750.tistory.com/222 ์ด ๋ฌธ์ ์ ๊ต์ฅํ ๋น์ทํ์!!
'2๏ธโฃ Java > Problem Solving' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Java Algorithm] ABCDE BOJ #13023 (0) | 2022.08.31 |
---|---|
[Java Algorithm] ์ ๋ก์์ฝ BOJ #10026 (0) | 2022.08.31 |
[Java Algorithm] ๋ น์ ์ท ์ ์ ์ ๊ฐ ์ ค๋ค์ง? (0) | 2022.08.31 |
[Java Algorithm] ๋ฏธ์ธ๋จผ์ง ์๋ ! BOJ #17144 (0) | 2022.08.31 |
[Java Algorithm] ์ฟผ๋ํธ๋ฆฌ BOJ #1992 (0) | 2022.08.18 |
๋๊ธ