LeetCode每日一题(Clone Graph)

该博客主要讨论了LeetCode中关于克隆无向图的题目。作者分享了早期尝试解决这个问题时遇到的困难,包括多次提交错误答案和超时问题。通过反思,作者认识到在处理图的复制问题时,使用广度优先搜索(BFS)通常比深度优先搜索(DFS)更为直观和高效。博客中详细解释了如何使用两次BFS来分别复制节点和建立新节点之间的连接,以完成图的深拷贝。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a reference of a node in a connected undirected graph.

Return a deep copy (clone) of the graph.

Each node in the graph contains a value (int) and a list (List[Node]) of its neighbors.

class Node {
public int val;
public List neighbors;
}

Test case format:

For simplicity, each node’s value is the same as the node’s index (1-indexed). For example, the first node with val == 1, the second node with val == 2, and so on. The graph is represented in the test case using an adjacency list.

An adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.

The given node will always be the first node with val = 1. You must return the copy of the given node as a reference to the cloned graph.

Example 1:

Input: adjList = [[2,4],[1,3],[2,4],[1,3]]
Output: [[2,4],[1,3],[2,4],[1,3]]

Explanation: There are 4 nodes in the graph.
1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).

Example 2:

Input: adjList = [[]]
Output: [[]]

Explanation: Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors.
Example 3:

Input: adjList = []
Output: []

Explanation: This an empty graph, it does not have any nodes.

Constraints:

  • The number of nodes in the graph is in the range [0, 100].
  • 1 <= Node.val <= 100
  • Node.val is unique for each node.
  • There are no repeated edges and no self-loops in the graph.
  • The Graph is connected and all nodes can be visited starting from the given node.

早期做这个题,提交了十几次,不是结果不对就是超时,现在回来看这个题,觉得经验真的很重要,当时一门心思的走 DFS 的路子,倒也不是不能做出来,但是代码会被搞的极为复杂,搞到最后自己可能猜到问题在哪了,但是改了之后会出现另一个问题。现在回过头来看,可能大部分的设计 Graph 的问题,BFS 才是更好而且更符合直觉的解决方式。这题用了两次 BFS 的遍历,一次复制 Node 本身, 一次给这些复制的 Node 添加关联。


func cloneGraph(node *Node) *Node {
	if node == nil {
		return nil
	}
	nexts := make([]*Node, 0, 100)
	nexts = append(nexts, node)
	nodes := make(map[int]*Node)
	visited := make(map[int]bool)
	for len(nexts) > 0 {
		n, remain := nexts[0], nexts[1:]
		nexts = remain
		if visited[n.Val] {
			continue
		}
		visited[n.Val] = true
		nodes[n.Val] = &Node{Val: n.Val}
		for _, neighbor := range n.Neighbors {
			if visited[n.Val] {
				nexts = append(nexts, neighbor)
			}
		}
	}
	visited = make(map[int]bool)
	nexts = make([]*Node, 0, 100)
	nexts = append(nexts, node)
	for len(nexts) > 0 {
		n, remain := nexts[0], nexts[1:]
		nexts = remain
		if visited[n.Val] {
			continue
		}
		visited[n.Val] = true
		for _, neighbor := range n.Neighbors {
			nodes[n.Val].Neighbors = append(nodes[n.Val].Neighbors, nodes[neighbor.Val])
		}
		for _, neighbor := range n.Neighbors {
			if visited[n.Val] {
				nexts = append(nexts, neighbor)
			}
		}
	}
	return nodes[node.Val]
}
### LeetCode Top 100 经典编程题目 LeetCode 上有许多经典的编程挑战,这些题目被广泛认为是掌握算法和数据结构的关键[^1]。以下是精选的一部分Top 100经典问题列表: #### 数组与字符串 1. **Two Sum** 2. **Add Two Numbers** 3. **Longest Substring Without Repeating Characters** #### 动态规划 4. **Climbing Stairs** 5. **Best Time to Buy and Sell Stock II** 6. **Unique Paths** #### 链表操作 7. **Merge Two Sorted Lists** 8. **Remove Nth Node From End of List** 9. **Reverse Linked List** #### 栈与队列 10. **Valid Parentheses** 11. **Min Stack** 12. **Implement Queue using Stacks** #### 排序与搜索 13. **Search Insert Position** 14. **Find First and Last Position of Element in Sorted Array** 15. **Sort Colors** #### 图论基础 16. **Clone Graph** 17. **Pacific Atlantic Water Flow** 18. **Number of Islands** #### 字符串处理 19. **String to Integer (atoi)** 20. **Valid Number** 21. **Decode Ways** #### 贪心算法 22. **Jump Game** 23. **Gas Station** 24. **Task Scheduler** 以上仅展示了部分LeetCode上被认为是经典的问题。对于完整的Top 100列表,建议访问官方推荐页面获取最新更新的信息。 ```python # 示例代码:验证括号的有效性 def isValid(s: str) -> bool: stack = [] mapping = {")": "(", "}": "{", "]": "["} for char in s: if char in mapping.values(): stack.append(char) elif char in mapping.keys(): if not stack or stack.pop() != mapping[char]: return False return len(stack) == 0 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值