문제 상황
There are n teams numbered from 0 to n - 1 in a tournament; each team is also a node in a DAG.
You are given the integer n and a 0-indexed 2D integer array edges of length m representing the DAG, where edges[i] = [ui, vi] indicates that there is a directed edge from team ui to team vi in the graph.
A directed edge from a to b in the graph means that team a is stronger than team b and team b is weaker than team a.
Team a will be the champion of the tournament if there is no team b that is stronger than team a.
Return the team that will be the champion of the tournament if there is a unique champion, otherwise, return -1.
Notes
- A cycle is a series of nodes a1, a2, ..., an, an+1 such that node a1 is the same node as node an+1, the nodes a1, a2, ..., an are distinct, and there is a directed edge from the node ai to node ai+1 for every i in the range [1, n].
- A DAG is a directed graph that does not have any cycle.
입력
- 1 <= n <= 100
- m == edges.length
- 0 <= m <= n * (n - 1) / 2
- edges[i].length == 2
- 0 <= edge[i][j] <= n - 1
- edges[i][0] != edges[i][1]
- The input is generated such that if team a is stronger than team b, team b is not stronger than team a.
- The input is generated such that if team a is stronger than team b and team b is stronger than team c, then team a is stronger than team c.
출력
챔피언이 나올 수 있는지 물어보는 나온다면 누구인지 안나온다면 -1을 리턴.
과정
풀이 : 위상정렬
확실한 연결고리는 있지만 모든 연결고리가 완벽하게 이어지지는 않음.
그러면 방법은 간단하게 DFS를 사용해 위상정렬을 한다. 중요한건 참조 개수에 해당하는 카운트가 0이었을때 즉 얘보다 약한애들의 모든 내용을 이미 돌아 본 뒤에 이 값의 카운터가 0이면서 얘보다 약한애가 없지않은 상태라면 이 노드는 챔피언일 수 있다는 개념, 다만 이 챔피언의 개수가 n개 이상일 수 있기 때문에 1개 이상일 경우엔 답을 -1로 한다.
알고리즘 개요도
알고리즘
class Solution {
vector<vector<int>> ans;
vector<int> cnt;
int answer = 101;
void DFS(int x)
{
cnt[x] = -1;
if (ans[x].empty())
{
if (answer == 101)
{
answer = x;
}
else
{
answer = -1;
}
return;
}
for (int arg : ans[x])
{
cnt[arg]--;
if (!cnt[arg])
{
DFS(arg);
}
}
}
public:
int findChampion(int n, vector<vector<int>>& edges) {
ans.resize(n, {});
cnt.resize(n, 0);
for (vector<int> edge : edges)
{
ans[edge[1]].push_back(edge[0]);
cnt[edge[0]]++;
}
// 시그널은 ans가 비어있는데 cnt가 0일경우
for (int i = 0; i < n; i++)
{
if (!cnt[i])
{
DFS(i);
}
}
return answer;
}
};
'알고리즘연구소👨💻 > 리트코드' 카테고리의 다른 글
1213. Intersection of Three Sorted Arrays (0) | 2024.11.25 |
---|---|
[Leetcode 1975번 문제] 1975. Maximum Matrix Sum (0) | 2024.11.24 |
[Leetcode 1861번 문제] 1861. Rotating the Box (0) | 2024.11.23 |
[Leetcode 1072번 문제] 1072. Flip Columns For Maximum Number of Equal Rows (0) | 2024.11.22 |
[Leetcode 2257번 문제] 2257. Count Unguarded Cells in the Grid (0) | 2024.11.21 |