R2-图
目录
DFS
BFS
ps:
图遍历即可,使用字典来记录访问过的结点。
DFS
"""
# Definition for a Node.
class Node:
def __init__(self, val = 0, neighbors = None):
self.val = val
self.neighbors = neighbors if neighbors is not None else []
"""
from typing import Optional
class Solution:
def cloneGraph(self, node: Optional['Node']) -> Optional['Node']:
#遍历整个图即可,已经访问的点,使用一个字典来记录
#DFS
look={}
def dfs(node):
if not node:
return
if node in look:
return look[node]
clone=Node(node.val,[])
look[node]=clone
for n in node.neighbors:
clone.neighbors.append(dfs(n))
return clone
return dfs(node)
BFS
"""
# Definition for a Node.
class Node:
def __init__(self, val = 0, neighbors = None):
self.val = val
self.neighbors = neighbors if neighbors is not None else []
"""
from typing import Optional
class Solution:
def cloneGraph(self, node: Optional['Node']) -> Optional['Node']:
#遍历整个图即可,已经访问的点,使用一个字典来记录
#BFS
look={}
def bfs(node):
if not node:
return
clone=Node(node.val,[])
look[node]=clone
queue=deque()
queue.appendleft(node)
while queue:
tmp=queue.pop()
for n in tmp.neighbors:
if n not in look:
look[n]=Node(n.val,[])
queue.appendleft(n)
look[tmp].neighbors.append(look[n])
return clone
return bfs(node)
ps:
很ok啊DFS和BFS