Create number_of_connected_components_in_a_undirected_graph.md#10
Create number_of_connected_components_in_a_undirected_graph.md#10tshimosake wants to merge 1 commit intomasterfrom
Conversation
| ```py | ||
| class Solution: | ||
| def countComponents(self, n: int, edges: List[List[int]]) -> int: | ||
| adj = [[] for _ in range(n)] |
There was a problem hiding this comment.
読むにあたり認知負荷が高くなるため、単語から文字を削って省略して変数名にするのは避けることをお勧めいたします。
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]: |
There was a problem hiding this comment.
条件を逆にして early return したほうが、ネストが浅くなり、読みやすくなると思います。
if visit[node]:
continue
visit[node] = True
dfs(node)
res += 1
There was a problem hiding this comment.
これはとてもよいですね。自分では思いつきませんでした。ありがとうございます!
| adj[v].append(u) | ||
|
|
||
| # 一つの連結成分内を走査する | ||
| def dfs(node): |
There was a problem hiding this comment.
関数名は動詞の命令形から始め、関数が行う処理を表す英単語・英語句を付けることをお勧めいたします。
また、ソフトウェアエンジニアの中で、 dfs という単語を見て、何のことかすぐに分かる人はあまり多くないように思います。
traverse() はいかがでしょうか?
There was a problem hiding this comment.
@nodchip コメントありがとうございます!traverseはよいですね!(1回目の答案は答えの丸写しなのでご容赦を、、、🙇♂️)
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/