Skip to content

Create number_of_connected_components_in_a_undirected_graph.md#10

Open
tshimosake wants to merge 1 commit intomasterfrom
tshimosake-patch-8
Open

Create number_of_connected_components_in_a_undirected_graph.md#10
tshimosake wants to merge 1 commit intomasterfrom
tshimosake-patch-8

Conversation

@tshimosake
Copy link
Owner

Number of Connected Components in an Undirected Graph
問題文:https://neetcode.io/problems/count-connected-components
leetcode はこちら(ただし課金が必要):https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/

```py
class Solution:
def countComponents(self, n: int, edges: List[List[int]]) -> int:
adj = [[] for _ in range(n)]
Copy link

Choose a reason for hiding this comment

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

読むにあたり認知負荷が高くなるため、単語から文字を削って省略して変数名にするのは避けることをお勧めいたします。

https://google.github.io/styleguide/pyguide.html#316-naming

avoid abbreviation. In particular, do not use abbreviations that are ambiguous or unfamiliar to readers outside your project, and do not abbreviate by deleting letters within a word.

# 複数(かもしれない)の連結成分それぞれに対し走査する
res = 0
for node in range(n):
if not visit[node]:
Copy link

Choose a reason for hiding this comment

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

条件を逆にして early return したほうが、ネストが浅くなり、読みやすくなると思います。

if visit[node]:
    continue
visit[node] = True
dfs(node)
res += 1

Copy link
Owner Author

Choose a reason for hiding this comment

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

これはとてもよいですね。自分では思いつきませんでした。ありがとうございます!

adj[v].append(u)

# 一つの連結成分内を走査する
def dfs(node):
Copy link

Choose a reason for hiding this comment

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

関数名は動詞の命令形から始め、関数が行う処理を表す英単語・英語句を付けることをお勧めいたします。

また、ソフトウェアエンジニアの中で、 dfs という単語を見て、何のことかすぐに分かる人はあまり多くないように思います。

traverse() はいかがでしょうか?

Copy link
Owner Author

Choose a reason for hiding this comment

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

@nodchip コメントありがとうございます!traverseはよいですね!(1回目の答案は答えの丸写しなのでご容赦を、、、🙇‍♂️)

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.

2 participants