[LeetCode] 2924. Find Champion II - Python

2024. 11. 27. 01:17·알고리즘/LeetCode

 

난이도: Medium

 

문제 설명


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.

 

문제 예제


Example 1:

Input: n = 3, edges = [[0,1],[1,2]]

Output: 0

Explanation: Team 1 is weaker than team 0. Team 2 is weaker than team 1. So the champion is team 0.

 

Example 2:

Input: n = 4, edges = [[0,2],[1,3],[1,2]]

Output: -1

Explanation: Team 2 is weaker than team 0 and team 1. Team 3 is weaker than team 1. But team 1 and team 0 are not weaker than any other teams. So the answer is -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.

 

✏️ Solution(솔루션)


class Solution:
    def findChampion(self, n: int, edges: List[List[int]]) -> int:
        if n == 1:
            return 0

        graph = [[] for _ in range(n)]

        for v1, v2 in edges:
            graph[v1].append(v2)

        for i in range(n):
            while True:
                before_len = len(graph[i])
                for v in graph[i]:
                    for vv in graph[v]:
                        if vv not in graph[i]:
                            graph[i].append(vv)
                if len(graph[i]) == n-1:
                    return i
                if before_len == len(graph[i]):
                    break

        return -1

 

먼저 주어진 edges를 통해 graph를 만들어주었다.

 

그 이후에는 단순히 그래프를 순회하면서 만약 2-->1 이라서 graph[2] = [1]로 저장되어 있다면, graph[2]에 graph[1]이 가지는 vertex Id를 추가해주었다.

예를 들어, graph[1] = [0, 3], graph[2] = [1] 이라고 한다면 2번 vertex는 1번을 이기기 때문에 1번 vertex가 이기는 0, 3번 vertex도 이긴다는 것이다. 따라서, graph[2] = [1, 0, 3]과 같이 저장하였다. 그 후 2번은 0번과 3번이 이기는 vertex도 이길 수 있기 때문에 같은 과정을 반복했다.

이러한 과정에서 graph[i]의 길이가 n-1이라고 한다면 i번 vertex가 챔피언인 것이다. 따라서 i를 반환하면 된다.

하지만 이전 graph[i]의 길이와 다시 연산을 수행했음에도 현재 graph[i]와 길이가 같다면 반복문을 탈출하게 구현하였다.

 

이 코드를 실행해서 제출했을 때 Accepted되긴 했지만, 실행 시간이 다른 유저들에 비해 오래 걸린다는 것을 확인했다.
확실히 단순하게 접근해서 그런지 좀 비효율적으로 코드를 짠듯한 느낌이 있다.

다음에 한번 다시 풀어봐야겠다.


[LeetCode] 2924. Find Champion II

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

[LeetCode] 1346. Check If N and Its Double Exist - Python  (0) 2024.12.01
[LeetCode] 3243. Shortest Distance After Road Addition Queries I - Python  (0) 2024.11.28
[LeetCode] 773. Sliding Puzzle - Python  (0) 2024.11.25
[LeetCode] 1861. Rotating the Box - Python  (0) 2024.11.23
[LeetCode] 2257. Count Unguarded Cells in the Grid - Python  (0) 2024.11.21
'알고리즘/LeetCode' 카테고리의 다른 글
  • [LeetCode] 1346. Check If N and Its Double Exist - Python
  • [LeetCode] 3243. Shortest Distance After Road Addition Queries I - Python
  • [LeetCode] 773. Sliding Puzzle - Python
  • [LeetCode] 1861. Rotating the Box - Python
Laewon Jeong
Laewon Jeong
  • Laewon Jeong
    래원
    Laewon Jeong
    글쓰기 | 관리
  • GitHub

    • github.com/laewonJeong
  • 전체
    오늘
    어제
    • 분류 전체보기 (172)
      • Docker 및 Kubernetes (11)
        • Docker (5)
        • Kubernetes (6)
      • Data Engineering (18)
        • Hadoop (5)
        • Spark (5)
        • Kafka (5)
        • Airflow (3)
      • CI|CD (3)
      • 알고리즘 (136)
        • 알고리즘 (2)
        • LeetCode (118)
        • 프로그래머스 (11)
        • BOJ (1)
        • 코딩테스트 대비 (4)
      • 서버 (2)
        • 미니 서버 (2)
      • 잡담 (1)
  • 태그

    heapq
    코딩테스트
    BFS
    Kubernetes
    String
    쿠버네티스
    알고리즘
    DP
    docker
    Python
    programmers
    그래프
    leetcode
    우선순위큐
    이진탐색
    분산
    티스토리챌린지
    누적합
    분산처리
    백트래킹
    오블완
    아파치 하둡
    파이썬
    dfs
    도커
    리트코드
    Apache Spark
    프로그래머스
    아파치 스파크
    문자열
  • 인기 글

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Laewon Jeong
[LeetCode] 2924. Find Champion II - Python
상단으로

티스토리툴바