
소스코드:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
static BufferedReader br;
static BufferedWriter bw;
static int height, width;
static char[][] board;
static boolean[][] visited;
static int startX, startY;
final static int[] dx = {0, 0, -1, 1};
final static int[] dy = {-1, 1, 0, 0};
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(br.readLine());
height = Integer.parseInt(st.nextToken());
width = Integer.parseInt(st.nextToken());
board = new char[height + 2][width + 2];
visited = new boolean[height + 2][width + 2];
for (int h = 0; h < height + 2; h++) {
Arrays.fill(board[h], 'X');
}
for (int y = 1; y <= height; y++) {
String line = br.readLine();
for (int x = 1; x <= width; x++) {
board[y][x] = line.charAt(x - 1);
if (board[y][x] == 'I') {
startX = x;
startY = y;
}
}
}
br.close();
int result = bfs();
bw.write((result != 0 ? result : "TT") + "\n");
bw.close();
}
private static int bfs() {
int result = 0;
Queue<int[]> queue = new LinkedList<>();
queue.add(new int[]{startX, startY});
visited[startY][startX] = true;
while (!queue.isEmpty()) {
int[] current = queue.poll();
int x = current[0];
int y = current[1];
if (board[y][x] == 'P') {
result++;
}
for (int i = 0; i < 4; i++) {
int targetX = x + dx[i];
int targetY = y + dy[i];
if (!visited[targetY][targetX] && board[targetY][targetX] != 'X') {
queue.add(new int[]{targetX, targetY});
visited[targetY][targetX] = true;
}
}
}
return result;
}
}
글의 내용 중 잘못된 점이나 수정이 필요한 부분, 혹은 궁금한 사항이 있다면 언제든 댓글로 남겨주시면 감사하겠습니다.
여러분의 피드백은 더 나은 글을 작성하는 데 큰 도움이 됩니다. 감사합니다.
'알고리즘 > 백준' 카테고리의 다른 글
| [JAVA-자바] 2667번: 단지번호붙이기 (0) | 2025.03.31 |
|---|---|
| [JAVA-자바] 2178번: 미로 탐색 (0) | 2025.03.28 |
| [JAVA-자바] 18111번: 마인크래프트 (0) | 2025.03.26 |
| [JAVA-자바] 7576번: 토마토 (0) | 2025.03.25 |
| [JAVA-자바] 1931번: 회의실 배정 (0) | 2025.03.25 |