Skip to content

323. Number of Connected Components in an Undirected Graph#21

Open
xbam326 wants to merge 3 commits into
mainfrom
323
Open

323. Number of Connected Components in an Undirected Graph#21
xbam326 wants to merge 3 commits into
mainfrom
323

Conversation

@xbam326
Copy link
Copy Markdown
Owner

@xbam326 xbam326 commented Jan 24, 2026

https://neetcode.io/problems/count-connected-components/question
で代用
## step1
- 絵が嘘つきすぎてて問題文読み間違えているのか何回も確認する羽目になった
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

自分は図のどこがおかしいのかよく分からないんですが、参考までにお聞きしても良いですか?

while connected_component:
connected_node = connected_component.pop()
for node in edge_dict[connected_node]:
if node not in unvisited:
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

逆の逆みたいなのは少し読みづらいですね

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

for文+visitedとかの方が個人的には見やすいかもしれません

connected_component_count += 1
connected_component = [node]

while connected_component:
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

connected_componentよりはunvisited_nodes_in_connected_componentという意味合いな気がしますね
unvisited_connected_nodesとかもありかもしれないです

node1, node2 = edge
uf.union(node1, node2)

root_nodes = set()
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

return len(set(uf.parents))でも行けそうです

class Solution:
def countComponents(self, n: int, edges: list[list[int]]) -> int:
unvisited_vertices = set(range(n))
vertex_to_neghbers = collections.defaultdict(set)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

neighborsですかね

vertex_to_neghbers = collections.defaultdict(set)
for vertex1, vertex2 in edges:
vertex_to_neghbers[vertex1].add(vertex2)
vertex_to_neghbers[vertex2].add(vertex1)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

ちなみにこれ片方だけでも書けますか

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