[Algorithm] 99클럽 코테 스터디 6일차 TIL | 백준_DFS와 BFS(1260번)

2025. 1. 20. 15:03·Algorithm

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


dfs와 bfs의 개념만 알고 있다면 풀 수 있는 문제

나는 2차원 배열에 입력값을 그대로 담아

간선 리스트를 사용하여 그래프를 표현하였다.

 

문제에 정점이 여러 개인 경우 정점 번호가 작은 것을 먼저 방문한다고 되어있어

2차원 배열을 정렬하여 문제를 풀었다.

for(int i = 0; i < M; i++){
    st = new StringTokenizer(br.readLine());
    map[i][0] = Integer.parseInt(st.nextToken());
    map[i][1] = Integer.parseInt(st.nextToken());
}
Arrays.sort(map, (a,b) -> {
    if(a[0] == b[0]){
        return a[1] - b[1];
    }
    return a[0] - b[0];
});

한 가지 간과하고 있던 문제는

입력값이 

5 3 1

1 5

3 5

5 2

로 들어올 때다.

 

기존 풀이에서 위와 같이 정렬했을 때 결과는 1 5 2 3이 나와야 되는데 1 5 3 2 가 나왔다

for(int i = 0; i < M; i++){
    st = new StringTokenizer(br.readLine());
    map[i][0] = Integer.parseInt(st.nextToken());
    map[i][1] = Integer.parseInt(st.nextToken());
    if(map[i][0] > map[i][1]){
        int temp = map[i][0];
        map[i][0] = map[i][1];
        map[i][1] = temp;
    }
}

그래서 배열의 첫번째 값에 가장 작은 값이 들어올 수 있도록 설정해주었다.

이렇게 하면 원하는 값을 얻을 수 있다,!

 

전체풀이

import java.util.*;
import java.io.*;
class Main{
    static StringBuilder answer = new StringBuilder();
    static int[][] map;
    static boolean[] visited;
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        int N = Integer.parseInt(st.nextToken());
        int M = Integer.parseInt(st.nextToken());
        int V = Integer.parseInt(st.nextToken());

        map = new int[M][2];
        for(int i = 0; i < M; i++){
            st = new StringTokenizer(br.readLine());
            map[i][0] = Integer.parseInt(st.nextToken());
            map[i][1] = Integer.parseInt(st.nextToken());
            if(map[i][0] > map[i][1]){
                int temp = map[i][0];
                map[i][0] = map[i][1];
                map[i][1] = temp;
            }
        }
        Arrays.sort(map, (a,b) -> {
            if(a[0] == b[0]){
                return a[1] - b[1];
            }
            return a[0] - b[0];
        });

        visited = new boolean[N+1];
        dfs(V, M);
        visited = new boolean[N+1];
        bfs(V, M);

        System.out.println(answer.toString());
    }

    public static void dfs(int n, int M){
        answer.append(n).append(" ");
        visited[n] = true;

        for(int i = 0; i < M; i++){
            if(!visited[map[i][1]] && map[i][0] == n){
                dfs(map[i][1], M);
            }else if(!visited[map[i][0]] && map[i][1] == n){
                dfs(map[i][0], M);
            }
        }
    }

    public static void bfs(int n, int M){
        Queue<Integer> queue = new LinkedList<>();
        queue.add(n);
        answer.append("\n").append(n);

        while(!queue.isEmpty()){
            int num = queue.poll();
            visited[num] = true;
            for(int i = 0; i < M; i++){
                if(!visited[map[i][1]] && map[i][0] == num){
                    queue.add(map[i][1]);
                    visited[map[i][1]] = true;
                    answer.append(" ").append(map[i][1]);
                }else if(!visited[map[i][0]] && map[i][1] == num){
                    queue.add(map[i][0]);
                    visited[map[i][0]] = true;
                    answer.append(" ").append(map[i][0]);
                }
            }
        }
    }
}

 

다른 분들 풀이가 대부분 인접 행렬을 사용하여 풀었길래!

이 방법으로도 풀이를 해봤다.

import java.util.*;
import java.io.*;
class Main{
    static StringBuilder answer = new StringBuilder();
    static boolean[][] graph;
    static boolean[] visited;
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        int N = Integer.parseInt(st.nextToken());
        int M = Integer.parseInt(st.nextToken());
        int V = Integer.parseInt(st.nextToken());

        graph = new boolean[N+1][N+1];
        for(int i = 0; i < M; i++){
            st = new StringTokenizer(br.readLine());
            int n1 = Integer.parseInt(st.nextToken());
            int n2 = Integer.parseInt(st.nextToken());
            graph[n1][n2] = true;
            graph[n2][n1] = true;
        }

        visited = new boolean[N+1];
        dfs(V, N);
        visited = new boolean[N+1];
        bfs(V, N);

        System.out.println(answer.toString());
    }

    public static void dfs(int n, int N){
        answer.append(n).append(" ");
        visited[n] = true;

        for(int i = 1; i <= N; i++){
            if(graph[n][i] && !visited[i]){
                dfs(i, N);
            }
        }
    }

    public static void bfs(int n, int N){
        Queue<Integer> queue = new LinkedList<>();
        queue.add(n);
        answer.append("\n");

        while(!queue.isEmpty()){
            int num = queue.poll();
            visited[num] = true;
            answer.append(num).append(" ");
            for(int i = 1; i <= N; i++){
                if(graph[num][i] && !visited[i]){
                    visited[i] = true;
                    queue.add(i);
                }
            }
        }
    }
}

간-결..

 

위에가 인접행렬, 아래가 간선리스트로 풀이한 결과다.

 

 

'Algorithm' 카테고리의 다른 글

[Algorithm] 99클럽 코테 스터디 8일차 TIL | 백준_단지번호붙이기(2667번)  (1) 2025.01.22
[Algorithm] 99클럽 코테 스터디 7일차 TIL | 백준_숨바꼭질(1697번)  (1) 2025.01.21
[Algorithm] 99클럽 코테 스터디 5일차 TIL | 백준_두 용액(2470번)  (0) 2025.01.17
[Algorithm] 99클럽 코테 스터디 4일차 TIL | 백준_기타 레슨(2343번)  (10) 2025.01.16
[Algorithm] 99클럽 코테 스터디 3일차 TIL | 백준_선분 위의 점(11663번)  (1) 2025.01.15
'Algorithm' 카테고리의 다른 글
  • [Algorithm] 99클럽 코테 스터디 8일차 TIL | 백준_단지번호붙이기(2667번)
  • [Algorithm] 99클럽 코테 스터디 7일차 TIL | 백준_숨바꼭질(1697번)
  • [Algorithm] 99클럽 코테 스터디 5일차 TIL | 백준_두 용액(2470번)
  • [Algorithm] 99클럽 코테 스터디 4일차 TIL | 백준_기타 레슨(2343번)
dev_ajrqkq
dev_ajrqkq
알고리즘 천재가 될 거야
  • dev_ajrqkq
    기록이 자산이다
    dev_ajrqkq
  • 전체
    오늘
    어제
    • 분류 전체보기 (147)
      • Front-end (0)
      • Back-end (11)
        • Spring (1)
        • Java (8)
      • CS (9)
        • 데이터베이스 (5)
        • 네트워크 (4)
      • Algorithm (80)
      • 이것저것 (0)
      • 버그잡기 (1)
      • TIL (37)
      • 후기 (1)
      • 취준 (0)
  • 블로그 메뉴

    • 링크

    • 공지사항

    • 인기 글

    • 태그

      티스토리챌린지
      개발자취업
      항해99
      코딩테스트준비
      99클럽
      Til
      TypeScript
      오블완
    • 최근 댓글

    • 최근 글

    • hELLO· Designed By정상우.v4.10.2
    dev_ajrqkq
    [Algorithm] 99클럽 코테 스터디 6일차 TIL | 백준_DFS와 BFS(1260번)
    상단으로

    티스토리툴바