Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

JAVA Developer Training

50. 1743번 음식물 피하기 본문

백준 알고리즘

50. 1743번 음식물 피하기

Romenest 2022. 1. 5. 20:12

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

 

1743번: 음식물 피하기

첫째 줄에 통로의 세로 길이 N(1 ≤ N ≤ 100)과 가로 길이 M(1 ≤ M ≤ 100) 그리고 음식물 쓰레기의 개수 K(1 ≤ K ≤ N×M)이 주어진다.  그리고 다음 K개의 줄에 음식물이 떨어진 좌표 (r, c)가 주어진다

www.acmicpc.net

 

풀었던 문제이다.

이번엔 다른 그래프 방식을 이용해서 풀어볼 생각

 

import java.io.*;

//1743
public class training13 {
    public static int N, M, K, cnt;
    public static int[][] map;
    public static boolean[][] visited;
    public static int[] dx = { 0, 1, 0, -1 };
    public static int[] dy = { 1, 0, -1, 0 };

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] string = br.readLine().split(" ");

        N = Integer.parseInt(string[0]);
        M = Integer.parseInt(string[1]);
        K = Integer.parseInt(string[2]);

        map = new int[N + 1][M + 1];
        visited = new boolean[N + 1][M + 1];
        // match error
        for (int i = 0; i < K; i++) {
            string = br.readLine().split(" ");
            int X = Integer.parseInt(string[0]) - 1;
            int Y = Integer.parseInt(string[1]) - 1;
            map[X][Y] = 1;
        }

        for (int i = 0; i < N; i++) {
            for (int j = 0; j < M; j++) {
                if (!visited[i][j] && map[i][j] == 1) {
                    int temp = cnt;
                    cnt = 0;
                    dfs(i, j);
                    cnt = Math.max(cnt, temp);
                }
            }
        }
        System.out.println(cnt);
    }

    public static void dfs(int a, int b) {
        visited[a][b] = true;
        cnt++;

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

            if (nx < 0 || ny < 0 || nx > N || ny > M) {
                continue;
            }
            if (!visited[nx][ny] && map[nx][ny] == 1) {
                visited[nx][ny] = true;
                dfs(nx, ny);
            }
        }
    }

}

 

결과

'백준 알고리즘' 카테고리의 다른 글

49. 2178번 미로탐색  (0) 2022.01.05
48. 1303번 전쟁-전투  (0) 2022.01.05
47. 8911번 거북이  (0) 2021.12.31
46. 1141번 접두사  (0) 2021.12.31
45. 2293번 동전 1  (0) 2021.12.20