문제
https://www.acmicpc.net/problem/21736
풀이(22분)
import java.awt.Point;
import java.io.*;
import java.util.*;
public class Main {
static int answer = 0;
static Queue<Point> queue = new LinkedList<>();
static int n;
static int m;
static char[][] arr ;
static int[][] direction = {{-1,0}, {1,0} , {0,-1}, {0,1}};
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
arr = new char[n][m];
for(int i = 0; i < n; i++){
String temp = br.readLine();
for(int j = 0; j < m; j++){
arr[i][j] = temp.charAt(j); // 띄어쓰기가 없기 때문에 다음과 같이 저장
if(arr[i][j] == 'I'){
queue.add(new Point(i,j)); // 출발점을 찾은 경우 바로 큐에 추가
}
}
}
bfs();
if(answer == 0){
System.out.println("TT"); // 0이면 출력 결과
return; // 반환을 통한 else문 생략
}
System.out.println(answer);
}
public static void bfs(){
while(!queue.isEmpty()){
Point point = queue.poll();
int nowX = point.x;
int nowY = point.y;
for(int i = 0; i < 4; i++){
int nextX = nowX + direction[i][0];
int nextY = nowY + direction[i][1];
if(nextX < n && nextX >= 0 && nextY >=0 && nextY < m){ // 이동 가능한 위치인지 파악
if(arr[nextX][nextY] == 'O'){ // 이동 가능하다면
arr[nextX][nextY] = 'X'; // 방문 처리하고
queue.add(new Point(nextX, nextY)); // 큐에 추가
continue; // 반복 검사 생략하기 위함
}
if(arr[nextX][nextY] == 'P'){ // 사람이라면
arr[nextX][nextY] = 'X'; // 방문처리하고
queue.add(new Point(nextX, nextY)); // 큐에 추가하고(방문 가능한 위치니까)
answer++; // 정답 + 1
}
}
}
}
}
}
평범한 bfs문제로 연습하기 매우 좋다고 생각한다.
'문제 풀이 > 백준' 카테고리의 다른 글
[백준] 17219번. 비밀번호 찾기(JAVA) (0) | 2024.11.18 |
---|---|
[백준] 6064번. 카잉 달력(JAVA) (0) | 2024.11.17 |
[백준] 1012번. 유기농 배추(JAVA) (1) | 2024.11.14 |
[백준] 18870번. 좌표 압축(JAVA) (0) | 2024.11.14 |
[백준] 1202번. 보석 도둑(JAVA) (0) | 2024.10.17 |