-
Notifications
You must be signed in to change notification settings - Fork 0
/
CloneGraph.php
64 lines (46 loc) · 1.2 KB
/
CloneGraph.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<?php
namespace QueueAndStack\StackAndDFS\CloneGraph;
// 给定连接的 无向图中的节点的引用 ,返回图的深拷贝(克隆)。图中的每个节点都包含val(int)和List[Node]其邻居的list()。
class Node {
public $val;
public $neighbors;
/**
* Node constructor.
*
* @param $val
* @param $neighbors Node[]
*/
function __construct($val, $neighbors) {
$this->val = $val;
$this->neighbors = $neighbors;
}
}
class Solution {
protected $map = [];
/**
* @param Node $node
* @return Node
*/
function cloneGraph($node) {
return $this->DFS($node);
}
protected function DFS($node)
{
/**
* @var $node Node
*/
if (is_null($node)) {
return null;
}
// 如果已经遍历过了
if (array_key_exists($node->val, $this->map)) {
return $this->map[$node->val];
}
$cloneNode = new Node($node->val, []);
$this->map[$node->val] = $cloneNode;
foreach ($node->neighbors as $n) {
$cloneNode->neighbors[] = $this->DFS($n);
}
return $cloneNode;
}
}