문제 풀이/백준

[백준] 21736번. 헌내기는 친구가 필요해(JAVA)

27200 2024. 11. 17. 11:15

문제

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문제로 연습하기 매우 좋다고 생각한다.