Skip to content

Conversation

@BangDori
Copy link
Member

@BangDori BangDori commented Jan 9, 2025

문제

Type Info
Time Complexity O(N)
Space Complexity O(N^2)
Algorithm DFS
Data Structure Array

Constraints

  • 1 <= n <= 10^5
  • 1 <= connections.length <= min(n * (n - 1) / 2, 10^5)
  • connections[i].length == 2
  • 0 <= ai, bi < n
  • ai != bi
  • There are no repeated connections.
  • No two computers are connected by more than one cable.

Edge Case

  1. 연결의 수(connections.length)가 n-1보다 작은 경우
  2. 연결이 그룹으로 나뉘어져 있는 경우

풀이

문제의 핵심은 케이블의 연결을 어떻게 변경해야 하는지가 아닌, "몇 개를 변경해야 하는지"

  1. 각 컴퓨터에 대한 방문 여부를 나타내는 배열 생성
  2. 연결이 필요한 카운터 변수 생성
  3. 0번 컴퓨터부터 시작해서 N번 컴퓨터까지 순회
    3-1. 만약 i번 컴퓨터가 이미 방문했다면 pass
    3-2. 방문하지 않았다면, 카운터를 1 더하고 dfs를 이용하여 방문 체크
  4. 최종적으로 카운터 - 1을 반환

카운터 - 1을 반환하는 이유는 시작 지점이 다른 지점과 연결되어 있더라도 반드시 시작 지점에 접근을 해야하기 때문에 -1을 하는 것

어려웠던 점

  • 단순 연결을 기준으로만 생각하고 문제에 접근해서, 그룹화되어 있는 연결들에 대한 체킹을 하지 못함

알게된 점

1. new Array(n).fill([])

const n = 3;
const graph = new Array(n).fill([]);
graph[0].push(1);

// graph = [ [1], [1], [1] ]

image

fill로 값을 채울 경우, 배열의 각 슬롯들이의 동일한 참조를 가지게 되면서 값을 공유하게 됨.

fill 메서드가 이렇게 동작하는 이유?

fill 메서드는 내부적으로 하나의 값만 생성하여 모든 슬롯에 그 값을 할당하는 방식을 가지고 있음. 그렇기 때문에 기본형인 primitve type이 아닌 객체가 오게 되면 객체의 참조가 복사되어 생성되게 되는 것

2. Array.from({ length: n }, () => [])

const n = 3;
const graph = Array.from({ length: n }, () => []);
graph[0].push(1);

// graph = [ [1], [], [] ]

image

인덱스마다 새로운 배열을 생성하기 때문에, 독립된 배열이 생성

@github-actions github-actions bot enabled auto-merge (squash) January 17, 2025 01:21
@github-actions github-actions bot merged commit 99ed9dd into main Jan 17, 2025
2 checks passed
@BangDori BangDori deleted the bangdori/number-of-operations-to-make-network-connected branch January 17, 2025 01:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants