koenjazh-CNfresde
짬뽕얼큰하게의 맨땅에 헤딩 :: Find Champion II

Find Champion II

알고리즘 2025. 2. 23. 08:36

Leetcode Problem:

Summary

  • Find the champion in a directed acyclic graph (DAG) tournament

Approach

  • Use depth-first search (DFS) to traverse the graph and identify the champion team
  • The champion team is the one that has no stronger team.

Complexity

  • O(n + m) where n is the number of teams and m is the number of edges in the graph

Solution Code:


class Solution {
public:
    vector adj[101];
    set leaf;
    bool visited[101];
    set start;
    void dfs(int cur){
        if(visited[cur]) return;
        visited[cur] = true;
        if(adj[cur].size() == 0){
            leaf.insert(cur);
            return;
        }
        for(int i = 0 ; i < adj[cur].size(); i++){
            int next = adj[cur][i];
            dfs(next);
        }
    }
    int findChampion(int n, vector>& edges) {
        if (n == 1) return 0;
        for(int  i = 0 ; i < edges.size(); i++){
            int a = edges[i][0];
            int b = edges[i][1];
            adj[b].push_back(a);
            start.insert(a);
            start.insert(b);
        }
        if(n != start.size()){
            return -1;
        }
        for(auto iter = start.begin(); iter != start.end(); iter++){
            dfs(*iter);
        }
        if(leaf.size() == 1) return *(leaf.begin());
        return -1;
    }
};

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

Construct Binary Tree from Preorder and Postorder Traversal  (0) 2025.02.23
Shortest Distance After Road Addition Queries I  (0) 2025.02.23
Recover a Tree From Preorder Traversal  (0) 2025.02.22
Sliding Puzzle  (0) 2025.02.22
Maximum Matrix Sum  (0) 2025.02.22
블로그 이미지

짬뽕얼큰하게

,