[C++] 백준/Gold/16724. 피리 부는 사나이

2025. 1. 14. 21:14·C++/Algorithm

문제: 음악 프로그램 (백준 16724번)

문제 분석

이번 문제는 주어진 그래프에서 사이클의 개수를 구하는 문제이다.

입력 형식을 보면 지도 밖으로 나가는 방향의 입력은 주어지지 않기 때문에 결국 화살표들은 사이클을 최소 1개 이상 무조건 생성을 하게 되어있다.

DFS를 사용한 사이클 개수 찾기

사이클 개수를 구하기 위해 DFS를 활용한다.
이때, 사이클 판별을 위해 visited와 finish 배열을 사용한다.

  1. visited[y][x]는 현재 칸이 방문되었는지 여부를 저장한다.
  2. finish[y][x]는 현재 칸에 대한 탐색이 끝났는지를 나타낸다.

DFS를 통해 현재 칸에서 다음 칸으로 이동하면서, 다음과 같은 조건으로 사이클을 판별한다.

  • 다음 칸이 방문된 적이 있지만 탐색이 끝나지 않은 칸이라면, 이는 사이클이 형성되었음을 의미한다.
  • 모든 탐색이 끝난 칸은 finish 배열에 표시하여 다시 방문하지 않도록 한다.

코드

#include <bits/stdc++.h>
using namespace std;

void dfs(int x, int y, vector<vector<pair<int, int>>>& graph, vector<vector<bool>>& finish, vector<vector<bool>>& visited, int& cycle) {
    visited[y][x] = true;

    int xx, yy; tie(yy, xx) = graph[y][x]; // 현재 칸에서 이동할 다음 칸
    if (!visited[yy][xx]) { 
        dfs(xx, yy, graph, finish, visited, cycle); // 다음 칸으로 이동
    }
    else if (!finish[yy][xx]) { 
        cycle++; // 사이클 발견
    }
    finish[y][x] = true; // 현재 칸 탐색 완료
}

int main() {
    ios::sync_with_stdio(0); cin.tie(0);
    int n, m; cin >> n >> m;
    vector<vector<pair<int,int>>> graph(n, vector<pair<int,int>>(m));

    // 그래프 초기화
    for (int i = 0; i < n; i++) {
        string s; cin >> s;
        for (int j = 0; j < m; j++) {
            char ch = s[j];
            if (ch == 'U') graph[i][j] = { i - 1, j };
            if (ch == 'D') graph[i][j] = { i + 1, j };
            if (ch == 'L') graph[i][j] = { i, j - 1 };
            if (ch == 'R') graph[i][j] = { i, j + 1 };
        }
    }

    vector<vector<bool>> visited(n, vector<bool>(m)), finish(n, vector<bool>(m));
    int answer = 0;

    // 모든 칸에 대해 DFS 실행
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (!visited[i][j]) {
                dfs(j, i, graph, finish, visited, answer);
            }
        }
    }
    cout << answer;
}

'C++ > Algorithm' 카테고리의 다른 글

[C++] 백준/Silver/1946. 신입 사원  (0) 2025.01.17
[C++] 백준/Gold/1918. 후위 표기식  (1) 2025.01.15
[C++] 백준/Gold/2623. 음악프로그램  (1) 2025.01.13
[C++] 백준/Gold/1202. 보석 도둑  (1) 2025.01.10
[C++] 백준/Gold/17143. 낚시왕  (1) 2025.01.09
'C++/Algorithm' 카테고리의 다른 글
  • [C++] 백준/Silver/1946. 신입 사원
  • [C++] 백준/Gold/1918. 후위 표기식
  • [C++] 백준/Gold/2623. 음악프로그램
  • [C++] 백준/Gold/1202. 보석 도둑
돼지표
돼지표
https://github.com/wkdgns135
  • 돼지표
    돼지표 개발 스토리
    돼지표
  • 전체
    오늘
    어제
    • 분류 전체보기 (101) N
      • C++ (59) N
        • Algorithm (53) N
      • Python (1)
      • Machine Learning (2)
      • Computer Graphics (4)
        • Curly Hair Simulation (2)
      • GPU Programming (11)
        • CUDA basic (7)
        • CUDA fluidsGL (4)
      • Unreal 5 (20)
        • Troubleshooting (4)
        • FPS Shooting (5)
        • Study (9)
        • EOS (1)
      • Computer Science (4) N
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

    • Github
  • 공지사항

  • 인기 글

  • 태그

    구현
    UE5
    C++
    그래프 탐색
    dp
    Fluid Simulation
    아이작 맵 생성
    그리디 알고리즘
    GPU Programming
    Algorithm
    수학
    FPS
    unreal 5
    위상 정렬
    Rendering Pipeline
    CUDA
    자료 구조
    OpenGL
    CS
    BFS
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
돼지표
[C++] 백준/Gold/16724. 피리 부는 사나이
상단으로

티스토리툴바