Skip to content

Commit 46cd561

Browse files
committed
'Clone Graph' soln
1 parent f5d2fdd commit 46cd561

File tree

2 files changed

+120
-1
lines changed

2 files changed

+120
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@ Note: Some solutions have multiple approaches implemented
136136
| 130 | [Surrounded Regions](https://leetcode.com/problems/surrounded-regions/) | [Solution](./leetcode/surrounded_regions.rs) | Medium |
137137
| 131 | [Palindrome Partitioning](https://leetcode.com/problems/palindrome-partitioning/) | [Solution](./leetcode/palindrome_partitioning.rs) | Medium |
138138
| 132 | [Palindrome Partitioning II](https://leetcode.com/problems/palindrome-partitioning-ii/) | [Solution](./leetcode/palindrome_partitioning_ii.rs) | Hard |
139-
| 133 | [Clone Graph](https://leetcode.com/problems/clone-graph/) | [Solution](./leetcode/clone_graph.rs) | Medium |
139+
| 133 | [Clone Graph]() | [Solution](./leetcode/clone_graph.rs) | Medium |
140140
| 134 | [Gas Station](https://leetcode.com/problems/gas-station/) | [Solution](./leetcode/gas_station.rs) | Medium |
141141
| 135 | [Candy](https://leetcode.com/problems/candy/) | [Solution](./leetcode/candy.rs) | Hard |
142142
| 136 | [Single Number](https://leetcode.com/problems/single-number/) | [Solution](./leetcode/single_number.rs) | Easy |

leetcode/clone_graph.rs

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
///
2+
/// Problem: Clone Graph
3+
///
4+
/// Given a reference of a node in a connected undirected graph, return a deep copy (clone) of the graph.
5+
///
6+
/// Each node in the graph contains a value (int) and a list (List[Node]) of its neighbors.
7+
///
8+
/// class Node {
9+
/// public int val;
10+
/// public List<Node> neighbors;
11+
/// }
12+
///
13+
/// Test case format:
14+
///
15+
/// For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first
16+
/// node with val == 1, the second node with val == 2, and so on. The graph is represented in the test
17+
/// case using an adjacency list.
18+
///
19+
/// An adjacency list is a collection of unordered lists used to represent a finite graph. Each list
20+
/// describes the set of neighbors of a node in the graph.
21+
///
22+
/// The given node will always be the first node with val = 1. You must return the copy of the given
23+
/// node as a reference to the cloned graph.
24+
///
25+
/// Example 1:
26+
/// Input: adjList = [[2,4],[1,3],[2,4],[1,3]]
27+
/// Output: [[2,4],[1,3],[2,4],[1,3]]
28+
/// Explanation: There are 4 nodes in the graph.
29+
/// 1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
30+
/// 2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
31+
/// 3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
32+
/// 4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
33+
///
34+
/// Example 2:
35+
/// Input: adjList = [[]]
36+
/// Output: [[]]
37+
/// Explanation: Note that the input contains one node with val = 1 and an empty list of neighbors.
38+
///
39+
/// Example 3:
40+
/// Input: adjList = []
41+
/// Output: []
42+
/// Explanation: This is an empty graph, it does not have any nodes.
43+
///
44+
/// Constraints:
45+
/// The number of nodes in the graph is in the range [0, 100].
46+
/// 1 <= Node.val <= 100
47+
/// Node.val is unique for each node.
48+
/// There are no repeated edges and no self-loops in the graph.
49+
/// The Graph is connected and all nodes can be visited starting from the given node.
50+
///
51+
52+
// Definition for a Node (as typically defined in this problem)
53+
// #[derive(Debug, Clone)]
54+
// pub struct Node {
55+
// pub val: i32,
56+
// pub neighbors: Vec<Option<Rc<RefCell<Node>>>>,
57+
// }
58+
//
59+
// impl Node {
60+
// #[inline]
61+
// pub fn new(val: i32) -> Self {
62+
// Node {
63+
// val,
64+
// neighbors: vec![],
65+
// }
66+
// }
67+
// }
68+
69+
// # Solution
70+
// Time complexity: O(V + E) where V is the number of vertices and E is the number of edges
71+
// Space complexity: O(V)
72+
73+
use std::rc::Rc;
74+
use std::cell::RefCell;
75+
use std::collections::HashMap;
76+
77+
impl Solution {
78+
pub fn clone_graph(node: Option<Rc<RefCell<Node>>>) -> Option<Rc<RefCell<Node>>> {
79+
if node.is_none() {
80+
return None;
81+
}
82+
83+
// HashMap to keep track of cloned nodes: original node -> cloned node
84+
let mut visited: HashMap<i32, Rc<RefCell<Node>>> = HashMap::new();
85+
86+
Self::dfs_clone(node, &mut visited)
87+
}
88+
89+
fn dfs_clone(
90+
node: Option<Rc<RefCell<Node>>>,
91+
visited: &mut HashMap<i32, Rc<RefCell<Node>>>
92+
) -> Option<Rc<RefCell<Node>>> {
93+
if let Some(n) = node {
94+
let val = n.borrow().val;
95+
96+
// If this node has already been cloned, return the clone
97+
if visited.contains_key(&val) {
98+
return Some(Rc::clone(&visited[&val]));
99+
}
100+
101+
// Create a new clone with the same value but empty neighbors
102+
let clone = Rc::new(RefCell::new(Node::new(val)));
103+
104+
// Mark as visited before processing neighbors to handle cycles
105+
visited.insert(val, Rc::clone(&clone));
106+
107+
// Clone all neighbors
108+
let neighbors = &n.borrow().neighbors;
109+
for neighbor in neighbors {
110+
let cloned_neighbor = Self::dfs_clone(neighbor.clone(), visited);
111+
clone.borrow_mut().neighbors.push(cloned_neighbor);
112+
}
113+
114+
Some(clone)
115+
} else {
116+
None
117+
}
118+
}
119+
}

0 commit comments

Comments
 (0)