백준 2606 바이러스 (실버3)

AI·2025년 10월 3일

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

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {
    static int n,m, cnt;
    static int[][] com;
    static boolean[][] vis;
    static int[] dx = {0,1,0,-1};
    static int[] dy = {1,0,-1,0};
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        n = Integer.parseInt(br.readLine());
        m = Integer.parseInt(br.readLine());
        com = new int[n+1][n+1];
        vis = new boolean[n+1][n+1];
        for(int i=0;i<m;i++){
            StringTokenizer st = new StringTokenizer(br.readLine());
            int a = Integer.parseInt(st.nextToken());
            int b = Integer.parseInt(st.nextToken());
            com[a][b] = 1; com[b][a] = 1;
        }
        dfs(1,1);
        System.out.println(cnt-1);
    }
    static void dfs(int x, int y){
        vis[x][y] = true;
        vis[y][x] = true;

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

            if(nx<1||nx>=n || ny<1 || ny>=n || vis[nx][ny] || vis[ny][nx]) continue;
            if(com[nx][ny]==1||com[ny][nx]==1) cnt++;
            dfs(nx,ny);
        }
    }
}

=> dfs라고 해서 dx, dy 같은 거에 같히지 말기. 그냥 로직만 알기

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {
    static int n,m, cnt;
    static int[][] com;
    static boolean[] vis;
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        n = Integer.parseInt(br.readLine());
        m = Integer.parseInt(br.readLine());
        com = new int[n+1][n+1];
        vis = new boolean[n+1];
        for(int i=0;i<m;i++){
            StringTokenizer st = new StringTokenizer(br.readLine());
            int a = Integer.parseInt(st.nextToken());
            int b = Integer.parseInt(st.nextToken());
            com[a][b] = 1; com[b][a] = 1;
        }
        dfs(1);
        System.out.println(cnt);
    }
    static void dfs(int x){
        vis[x] = true;

        for(int d=1;d<=n;d++){
            if(com[x][d]==1 && !vis[d]){
                cnt++;
                dfs(d);
            }
        }
    }
}

0개의 댓글