[LeetCode] 399. Evaluate Division, Medium

2025. 4. 29. 14:00·CodingTest/LeetCode
반응형

1. 문제

  • equitions에 문자열 2차원 배열이 주어지고, 각 문자열을 나눈 값을 담은 배열 values가 주어질 때, queries의 나눈 값을 담은 배열을 반환하라.
  • 존재할 수 없는 경우는 -1.0을 담아야 한다.

2. 해결

function calcEquation(
    equations: string[][],
    values: number[],
    queries: string[][]
): number[] {
    const graph = new Map<string, [string, number][]>();

    // 그래프 만들기
    for (let i = 0; i < equations.length; i++) {
        const [a, b] = equations[i];
        const value = values[i];

        if (!graph.has(a)) graph.set(a, []);
        if (!graph.has(b)) graph.set(b, []);

        graph.get(a)!.push([b, value]);     // a -> b (value)
        graph.get(b)!.push([a, 1 / value]); // b -> a (1/value)
    }

    // DFS 함수
    const dfs = (
        current: string,
        target: string,
        visited: Set<string>,
        acc: number
    ): number => {
        if (!graph.has(current) || !graph.has(target)) return -1.0;
        if (current === target) return acc;

        visited.add(current);

        for (const [neighbor, value] of graph.get(current)!) {
            if (!visited.has(neighbor)) {
                const result = dfs(neighbor, target, visited, acc * value);
                if (result !== -1.0) return result;
            }
        }

        return -1.0;
    };

    // 쿼리 처리
    const results: number[] = [];

    for (const [a, b] of queries) {
        const visited = new Set<string>();
        results.push(dfs(a, b, visited, 1));
    }

    return results;
}
  • 못풀었다.
  • 원리는 각 문자열의 비율을 이용해 역수를 구하여 map에 저장하여 그래프 형태로 만든다.
    • a/b = 2.0이면 b/a = 1/2.0이 된다.
  • queries의 문자열을 탐색하면서, 그래프를 DFS 탐색해 구한다. a/c의 경우 a/b * b/c를 통해 구할 수 있다.
저작자표시 (새창열림)
'CodingTest/LeetCode' 카테고리의 다른 글
  • [LeetCode] 994. Rotting Oranges, Medium
  • [LeetCode] 1926. Nearest Exit from Entrance in Maze, Medium
  • [LeetCode] 1466. Reorder Routes to Make All Paths Lead to the City Zero, Medium
  • [LeetCode] 547. Number of Provinces, Medium
뜸부깅
뜸부깅
코딩에 대한 여러 개인적인 생각을 정리하고 공부를 하는 공간입니다!!
  • 뜸부깅
    코오오딩
    뜸부깅
  • 전체
    오늘
    어제
    • Note (429)
      • Skill (31)
        • Java & Spring (9)
        • Javascript & HTML & CSS (0)
        • React (0)
        • Next.js (22)
      • CodingTest (389)
        • 백준 온라인 저지(BOJ) (140)
        • 프로그래머스(Programmers) (79)
        • LeetCode (170)
      • Algorithm & Data Structure (6)
      • [Project] 포트폴리오 (3)
        • Front end (3)
        • Back end (0)
  • 블로그 메뉴

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

  • 공지사항

  • 인기 글

  • 태그

    meidum
    component-scan
    백준1260
    알고리즘
    boj1427
    자바
    백준2751
    BOJ
    next 14
    프로그래머스
    Easy
    leetcode 2236
    medium
    Java
    백준
    백준7576
    TypeScript
    백준1427
    백준7576자바
    boj2108
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
뜸부깅
[LeetCode] 399. Evaluate Division, Medium
상단으로

티스토리툴바