[Leetcode - Medium] Number of Operations to Make Network Connected #50
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
문제
Constraints
1 <= n <= 10^51 <= connections.length <= min(n * (n - 1) / 2, 10^5)connections[i].length == 20 <= ai, bi < nai != biEdge Case
connections.length)가 n-1보다 작은 경우풀이
문제의 핵심은 케이블의 연결을 어떻게 변경해야 하는지가 아닌, "몇 개를 변경해야 하는지"
3-1. 만약 i번 컴퓨터가 이미 방문했다면 pass
3-2. 방문하지 않았다면, 카운터를 1 더하고 dfs를 이용하여 방문 체크
카운터 - 1을 반환하는 이유는 시작 지점이 다른 지점과 연결되어 있더라도 반드시 시작 지점에 접근을 해야하기 때문에 -1을 하는 것
어려웠던 점
알게된 점
1.
new Array(n).fill([])fill로 값을 채울 경우, 배열의 각 슬롯들이의 동일한 참조를 가지게 되면서 값을 공유하게 됨.fill메서드가 이렇게 동작하는 이유?fill메서드는 내부적으로 하나의 값만 생성하여 모든 슬롯에 그 값을 할당하는 방식을 가지고 있음. 그렇기 때문에 기본형인 primitve type이 아닌 객체가 오게 되면 객체의 참조가 복사되어 생성되게 되는 것2.
Array.from({ length: n }, () => [])인덱스마다 새로운 배열을 생성하기 때문에, 독립된 배열이 생성