did_story
[ํ๋ก๊ทธ๋๋จธ์ค / Java] ๊ฑฐ๋ฆฌ๋๊ธฐ ํ์ธํ๊ธฐ ๋ณธ๋ฌธ
Algorithm๐/ํ๋ก๊ทธ๋๋จธ์ค(Programmers)
[ํ๋ก๊ทธ๋๋จธ์ค / Java] ๊ฑฐ๋ฆฌ๋๊ธฐ ํ์ธํ๊ธฐ
์ด์ ์์ 2025. 9. 29. 01:53๋ฌธ์ ๋ ๋จ์ํ๊ฒ ๋ณผ์ ์๋ค.
๋ฌธ์ ์ค๋ช
์ฝ๋ก๋ ๋ฐ์ด๋ฌ์ค ๊ฐ์ผ ์๋ฐฉ์ ์ํด ์์์๋ค์ ๊ฑฐ๋ฆฌ๋ฅผ ๋ฌ์ ๋๊ธฐ๋ฅผ ํด์ผํ๋๋ฐ ๊ฐ๋ฐ ์ง๊ตฐ ๋ฉด์ ์ธ ๋งํผ
์๋์ ๊ฐ์ ๊ท์น์ผ๋ก ๋๊ธฐ์ค์ ๊ฑฐ๋ฆฌ๋ฅผ ๋๊ณ ์๋๋ก ์๋ดํ๊ณ ์์ต๋๋ค.
๋๊ธฐ์ค์ 5๊ฐ์ด๋ฉฐ, ๊ฐ ๋๊ธฐ์ค์ 5x5 ํฌ๊ธฐ์ ๋๋ค.
๊ฑฐ๋ฆฌ๋๊ธฐ๋ฅผ ์ํ์ฌ ์์์๋ค ๋ผ๋ฆฌ๋ ๋งจํดํผ ๊ฑฐ๋ฆฌ๊ฐ 2 ์ดํ๋ก ์์ง ๋ง์ ์ฃผ์ธ์.
๋จ ์์์๊ฐ ์์์๋ ์๋ฆฌ ์ฌ์ด๊ฐ ํํฐ์ ์ผ๋ก ๋งํ ์์ ๊ฒฝ์ฐ์๋ ํ์ฉํฉ๋๋ค.
ํด๊ฒฐ๋ฒ.
๊ฐ ‘P’์ ๋ํด:
๋งจํดํผ ๊ฑฐ๋ฆฌ 2 ์ด๋ด์์, 'O'๋ ๊ฑฐ๋ฆฌ<2์ผ ๋๋ง ํ์ฅํ๋ฉฐ ํ์ํ๋ค.
ํ์ ๋์ค ๋ค๋ฅธ 'P'๋ฅผ ๋ง๋๋ฉด ์ฆ์ ์๋ฐ.
'X'์ ๊ฒฝ์ฐ๋ ์๊ฐํ์ง ์์๋ ๋๋ค๊ณ ํ๋จ (๋ง๋๋ฉด ๊ทธ๊ณณ์ ๋ชป์ง๋๊ฐ๋๊น.)
์ฝ๋
import java.util.LinkedList;
import java.util.Queue;
class Solution {
public int[] solution(String[][] places) {
int[] answer = new int[places.length];
for (int i = 0; i < places.length; i++) {
boolean ok = true;
String[] p = places[i];
out:
for (int r = 0; r < 5; r++) {
for (int c = 0; c < 5; c++) {
if (p[r].charAt(c) == 'P') {
if (bfs(r, c, p)) {
ok = false;
break out;
}
}
}
}
answer[i] = ok ? 1 : 0;
}
return answer;
}
private static boolean bfs(int r, int c, String[] p){
int[] dr = {-1, 1, 0, 0};
int[] dc = {0, 0, -1, 1};
Queue<int[]> q = new LinkedList<int[]>();
q.offer(new int[]{r, c});
while(!q.isEmpty()){
int[] position = q.poll();
for (int i = 0 ; i < 4 ; i ++){
int nowR = position[0] + dr[i];
int nowC = position[1] + dc[i];
if (nowR < 0 || nowC < 0 || nowR >= 5 || nowC >= 5 || (nowR == r && nowC == c)) continue;
int d = Math.abs(nowR - r) + Math.abs(nowC - c);
if (d <= 2 && p[nowR].charAt(nowC) == 'P') return true;
else if (d < 2 && p[nowR].charAt(nowC) == 'O') q.offer(new int[]{nowR, nowC});
}
}
return false;
}
}
ํ๊ณ
bfs๋ผ๊ณ ๋น ๋ฅด๊ฒ ์ ๊ทผ ํ ๋ฌธ์ ๋ฅผ ๋ฐ์ ๋๋ ค์, ์๊ฐ๋ณด๋ค ๋น ๋ฅด๊ฒ ํผ ๊ฐ์ด ์๋ค. ๋ฌผ๋ก ์ค๊ฐ์ค๊ฐ BFS ์ด๋ป๊ฒ ๋ง๋ค๋๋ผ๋ ์๊ฐ์ด ์์์ง๋ง... BFS ๋ก์ง์ ์๊น๋จน๊ณ ์์ด์ ๋คํ์ด๋ค.
'Algorithm๐ > ํ๋ก๊ทธ๋๋จธ์ค(Programmers)' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| [ํ๋ก๊ทธ๋๋จธ์ค / JAVA] ํ ํธ์ง (0) | 2025.10.09 |
|---|---|
| [ํ๋ก๊ทธ๋๋จธ์ค / JAVA] ๋๋๊ณผ ๋ง๋ ๊ทธ๋ํ. (0) | 2025.09.30 |
| [ํ๋ก๊ทธ๋๋จธ์ค / ์๋ฐ] ๊ณต์์ฐ์ฑ (0) | 2025.09.12 |
| [ํ๋ก๊ทธ๋๋จธ์ค / JAVA] JadenCase ๋ฌธ์์ด ๋ง๋ค๊ธฐ (3) | 2025.07.10 |
| [ํ๋ก๊ทธ๋๋จธ์ค / JAVA ] ์คํจ์จ (2) | 2025.07.09 |