본문 바로가기

알고리즘

[BOJ] 1260번 : DFS와 BFS (JAVA)

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

 

1260번: DFS와 BFS

첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사

www.acmicpc.net

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


public class hy {


    static Queue<Integer> queue = new LinkedList<>();
    static int N, M, V;
    static boolean[][] map;
    static boolean[] visited;
    static void dfs(int x){
        if(visited[x]) return;

        visited[x]=true; //방문체크
        System.out.print(x+" ");
        for(int i=1;i<=N;i++){
            if(!visited[i]&&map[i][x]&&map[x][i]){
                dfs(i);
            }
        }

    }

    static void bfs(int x){

        visited[x]=true;

        while(!queue.isEmpty()){
            int tmp = queue.poll();
            System.out.print(tmp+" ");
            for(int i=1;i<=N;i++){
                if(!visited[i]&&map[i][tmp]&&map[tmp][i]){
                    queue.add(i);
                    visited[i]=true;
                }
            }
        }

    }
    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());
        V = Integer.parseInt(st.nextToken());
        map = new boolean[N+1][N+1];
        visited = new boolean[N+1];

        for(int i=0;i<M;i++){
            st = new StringTokenizer(br.readLine());
            int x = Integer.parseInt(st.nextToken());
            int y = Integer.parseInt(st.nextToken());
            map[x][y]=true;
            map[y][x]=true;
        }


        //dfs
        dfs(V);

        System.out.println();
        //bfs
        queue.add(V);
        for(int i=0;i<=N;i++){
            visited[i]=false;
        }
        bfs(V);

    }
}

 

인접행렬은 대각선 기준 대칭이기 때문에 열이나 행 하나만 검사해도 될 것 같다.

DFS, BFS 기본중에 기본인 문제지만 못 풀던 문제를 풀어내서 기분이 좋다 ! 캬캬