Skip to content

3651 · Number of Connected Components in an Undirected Graph#19

Open
tarinaihitori wants to merge 1 commit into
mainfrom
3651-number-of-connected-components-in-an-undirected-graph
Open

3651 · Number of Connected Components in an Undirected Graph#19
tarinaihitori wants to merge 1 commit into
mainfrom
3651-number-of-connected-components-in-an-undirected-graph

Conversation

@tarinaihitori
Copy link
Copy Markdown
Owner

この問題がLeetCode Premiumの問題だったため、類題を解いた。

Description
In this problem, there is an undirected graph with n nodes. There is also an edges array. Where edges[i] = [a, b] means that there is an edge between node a and node b in the graph.
You need to return the number of connected components in that graph.

Example
Example 1
Input:3
[[0,1], [0,2]]
Output:1

Example 2
Input:6
[[0,1], [1,2], [2, 3], [4, 5]]
Output:2

類題のURL
https://www.lintcode.com/problem/3651/description

元の問題のURL(プレミアム)
https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/description/

Comment on lines 85 to 86
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

stack = [node_index]

でも。

stack という名前、気に入らない人もいるかもしれませんが、私は比較的許容で、というのも「node_index から visit_connected_nodes します。そのために、まず、積む場所を用意して、node_index をいれます。」と言われたら、connected_nodes が積まれるのだろうな、と文脈から「積む」の意味が推測できるからです。

そうでない人がいたらコメントを書くか変数名をもう少し説明的にするかですね。

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

visited_node_indexes は visit_connected_nodes 定義より前で宣言してもいいでしょう。adjacency_list も。visit_connected_nodes で使うので。

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

今回の問題設定においては、node_indexってすなわちnodeなのでは?とおもいました

確かにランダムアクセスのindexとしても使っているのですが、node_indexと表現しなくてもそれは自明かなと思いました

Comment on lines 182 to 184
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

一応
UnionFind内にcomponent_countみたいなメンバを持っておいて、rootが異なるnodeに対してunionが呼ばれたとき減算していくと、各edgeに対してunionした後すぐcomponent countを引き出せます

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.

3 participants