백준 2636 치즈(JAVA)

2024. 8. 7. 17:05·PS(Problem Solving)/JAVA

문제 설명

https://www.acmicpc.net/problem/2636

 

풀이과정

 DFS를 이용해서 풀이했다.

 

정답코드

import java.io.*;
import java.util.*;

public class Main {

    static int[] dy = {-1, 1, 0, 0};
    static int[] dx = {0, 0, -1, 1};
    static int N, M;
    static int[][] board;
    static boolean[][] visited;
    static int cheeseCnt = 0;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        StringTokenizer st = new StringTokenizer(br.readLine());

        N = Integer.parseInt(st.nextToken());
        M = Integer.parseInt(st.nextToken());

        board = new int[N][M];

        for (int i = 0; i < N; i++) {
            st = new StringTokenizer(br.readLine());

            for (int j = 0; j < M; j++) {
                board[i][j] = Integer.parseInt(st.nextToken());
                if (board[i][j] == 1) {
                    cheeseCnt++;
                }
            }
        }

        int currentCheeseCnt = 0;
        int time = 0;

        while (cheeseCnt > 0) {
            currentCheeseCnt = cheeseCnt;
            time++;
            visited = new boolean[N][M];
            dfs(0, 0);
        }

        bw.write(time + "\n" + currentCheeseCnt);
        bw.flush();
    }

    public static void dfs(int y, int x) {

        if (visited[y][x]) {
            return;
        }

        visited[y][x] = true;

        for (int i = 0; i < 4; i++) {
            int ny = y + dy[i];
            int nx = x + dx[i];

            if (ny >= 0 && ny < N && nx >= 0 && nx < M) {
                if (!visited[ny][nx]) {
                    if (board[ny][nx] == 0) {
                        dfs(ny, nx);
                    } else if (board[ny][nx] == 1) {
                        board[ny][nx] = 0;
                        cheeseCnt--;
                        visited[ny][nx] = true;
                    }
                }
            }
        }

    }
}
저작자표시 비영리 변경금지 (새창열림)
'PS(Problem Solving)/JAVA' 카테고리의 다른 글
  • 백준 17298 오큰수(JAVA)
  • 백준 1068 트리(JAVA)
  • 백준 14502 연구소(JAVA)
  • 백준 4949 균형잡힌 세상(JAVA)
SiwonHae
SiwonHae
프로그래밍을 공부하고 있는 학생입니다.
  • SiwonHae
    시원해의 블로그
    SiwonHae
  • 전체
    오늘
    어제
    • 전체보기 (150)
      • PS(Problem Solving) (95)
        • C (25)
        • C++ (33)
        • JAVA (37)
      • Algorithm & Data Structure (13)
      • Computer Science (12)
        • Network (2)
        • Design Pattern (10)
      • Back-end (6)
        • Spring (5)
      • Front-end (1)
        • React (1)
      • JAVA (4)
      • 정보처리기사 (17)
      • SQLD (2)
  • 블로그 메뉴

    • 홈
    • 방명록
    • 글쓰기
  • 인기 글

  • 최근 댓글

  • hELLO· Designed By정상우.v4.10.0
SiwonHae
백준 2636 치즈(JAVA)
상단으로

티스토리툴바