Skip to content

[JustDevRae] 25.02.22#47

Merged
JooKangsan merged 40 commits intomainfrom
JustDevRae
Feb 27, 2025
Merged

[JustDevRae] 25.02.22#47
JooKangsan merged 40 commits intomainfrom
JustDevRae

Conversation

@JustDevRae
Copy link
Collaborator

📌 푼 문제


📝 간단한 풀이 과정

Find the Town Judge

각 사람의 신뢰 점수를 배열에 집계한 후, 배열을 순회하며 신뢰 점수가 n - 1인 사람을 찾아 반환하는 방식으로 해결했습니다.

var findJudge = function (n, trust) {
  if (n === 1) return 1;

  const trustScore = new Array(n + 1).fill(0);

  for (const [a, b] of trust) {
    trustScore[a]--;
    trustScore[b]++;
  }

  for (let i = 1; i <= n; i++) {
    if (trustScore[i] === n - 1) return i;
  }

  return -1;
};

Find if Path Exists in Graph

edges를 인접 리스트로 변환한 후, BFS 큐를 활용해 시작 노드에서 목표 노드까지 경로가 존재하는지를 탐색하는 방식으로 해결했습니다.

var validPath = function (n, edges, source, destination) {
  const adjacencyList = new Array(n).fill(0).map(() => []);
  for (const [nodeA, nodeB] of edges) {
    adjacencyList[nodeA].push(nodeB);
    adjacencyList[nodeB].push(nodeA);
  }

  const visitedNodes = new Array(n).fill(false);
  const bfsQueue = [source];
  visitedNodes[source] = true;

  while (bfsQueue.length) {
    const currentNode = bfsQueue.shift();
    if (currentNode === destination) return true;

    for (const adjacentNode of adjacencyList[currentNode]) {
      if (!visitedNodes[adjacentNode]) {
        visitedNodes[adjacentNode] = true;
        bfsQueue.push(adjacentNode);
      }
    }
  }

  return false;
};

게임 맵 최단거리

미로 지도를 2차원 배열로 해석한 후, 이동 방향 배열을 이용해 BFS로 최단 경로를 탐색하고 도착 지점까지의 이동 횟수를 계산하는 방식으로 해결했습니다.

function solution(maps) {
  const n = maps.length;
  const m = maps[0].length;

  const dx = [0, 0, 1, -1];
  const dy = [1, -1, 0, 0];

  let queue = [];
  queue.push([0, 0]);

  while (queue.length) {
    const [y, x] = queue.shift();

    if (y === n - 1 && x === m - 1) {
      return maps[y][x];
    }

    for (let i = 0; i < 4; i++) {
      const ny = y + dy[i];
      const nx = x + dx[i];

      if (ny >= 0 && ny < n && nx >= 0 && nx < m && maps[ny][nx] === 1) {
        maps[ny][nx] = maps[y][x] + 1;
        queue.push([ny, nx]);
      }
    }
  }

  return -1;
}

타겟 넘버

숫자 배열을 DFS 기법으로 재귀 탐색한 후, 모든 경우의 수 중 목표 숫자에 도달하는 경우를 누적하여 카운트하는 방식으로 해결했습니다.

function solution(numbers, target) {
  let count = 0;

  function DFS(index, currentSum) {
    if (index === numbers.length) {
      if (currentSum === target) count++;
      return;
    }

    DFS(index + 1, currentSum + numbers[index]);
    DFS(index + 1, currentSum - numbers[index]);
  }

  DFS(0, 0);

  return count;
}

배달

도로 정보를 그래프로 구성한 후, 다익스트라 알고리즘을 활용해 시작 마을에서 각 마을까지의 최단 이동 시간을 계산하고, 제한 시간 내 도달 가능한 마을의 수를 집계하는 방식으로 해결했습니다.

function solution(N, road, K) {
  const graph = Array.from({ length: N + 1 }, () => []);
  for (const [a, b, c] of road) {
    graph[a].push({ node: b, cost: c });
    graph[b].push({ node: a, cost: c });
  }

  const distance = new Array(N + 1).fill(Infinity);
  distance[1] = 0;

  const visited = new Array(N + 1).fill(false);

  for (let i = 1; i <= N; i++) {
    let current = -1;

    for (let j = 1; j <= N; j++) {
      if (!visited[j] && (current === -1 || distance[j] < distance[current])) {
        current = j;
      }
    }

    if (current === -1) break;

    visited[current] = true;

    for (const { node, cost } of graph[current]) {
      if (distance[node] > distance[current] + cost) {
        distance[node] = distance[current] + cost;
      }
    }
  }
  return distance.filter((time) => time <= K).length;
}

Copy link
Collaborator

@Moonjonghoo Moonjonghoo left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

전체적으로 탐색과 배열을 잘 활용해서 풀어주신거같습니다!
고생하셨습니다.

Copy link
Collaborator

@bona1122 bona1122 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

코드 잘 보았습니다. dfs,bfs,다익스트라 모두 잘 이용하신 것 같습니다! 한주동안 수고하셨습니다😊

@JooKangsan JooKangsan merged commit a495e21 into main Feb 27, 2025
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants