题意:

image.png

解题思路:

  1. 思路:DFS

PHP代码实现:

  1. /*
  2. // Definition for a Node.
  3. class Node {
  4. public $val;
  5. public $neighbors;
  6. @param Integer $val
  7. @param list<Node> $neighbors
  8. function __construct($val, $neighbors) {
  9. $this->val = $val;
  10. $this->neighbors = $neighbors;
  11. }
  12. }
  13. */
  14. class Solution {
  15. /**
  16. * @param Node $node
  17. * @return Node
  18. */
  19. function cloneGraph($node) {
  20. $map = new SplObjectStorage();
  21. return $this->dfs($node, $map);
  22. }
  23. function dfs($node, &$map) {
  24. if($node == null) return null;
  25. if($map->contains($node)) return $map[$node];
  26. $clone = new Node($node->val, []);
  27. $map[$node] = $clone;
  28. foreach($node->neighbors as $neighbor){
  29. $clone->neighbors[] = $this->dfs($neighbor, $map);
  30. }
  31. return $clone;
  32. }
  33. }

GO代码实现:

  1. /**
  2. * Definition for a Node.
  3. * type Node struct {
  4. * Val int
  5. * Neighbors []*Node
  6. * }
  7. */
  8. func cloneGraph(node *Node) *Node {
  9. visited := make(map[*Node]*Node)
  10. return cloneNode(node, visited)
  11. }
  12. func cloneNode(node *Node, visited map[*Node]*Node) *Node {
  13. if node == nil {
  14. return nil
  15. }
  16. if n, ok := visited[node]; ok {
  17. return n
  18. }
  19. c := &Node{Val: node.Val}
  20. visited[node] = c
  21. for _, ne := range node.Neighbors {
  22. c.Neighbors = append(c.Neighbors, cloneNode(ne, visited))
  23. }
  24. return c
  25. }