Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions solution/0800-0899/0847.Shortest Path Visiting All Nodes/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,45 @@ public:
};
```

### **Rust**

```rust
use std::collections::VecDeque;

impl Solution {
#[allow(dead_code)]
pub fn shortest_path_length(graph: Vec<Vec<i32>>) -> i32 {
let n = graph.len();
let mut vis = vec![vec![false; 1 << n]; n];
let mut q = VecDeque::new();

// Initialize the queue
for i in 0..n {
q.push_back(((i, 1 << i), 0));
vis[i][1 << i] = true;
}

// Begin BFS
while !q.is_empty() {
let ((i, st), count) = q.pop_front().unwrap();
if st == ((1 << n) - 1) {
return count;
}
// If the path has not been visited
for j in &graph[i] {
let nst = st | (1 << *j);
if !vis[*j as usize][nst] {
q.push_back(((*j as usize, nst), count + 1));
vis[*j as usize][nst] = true;
}
}
}

-1
}
}
```

### **Go**

```go
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,45 @@ public:
};
```

### **Rust**

```rust
use std::collections::VecDeque;

impl Solution {
#[allow(dead_code)]
pub fn shortest_path_length(graph: Vec<Vec<i32>>) -> i32 {
let n = graph.len();
let mut vis = vec![vec![false; 1 << n]; n];
let mut q = VecDeque::new();

// Initialize the queue
for i in 0..n {
q.push_back(((i, 1 << i), 0));
vis[i][1 << i] = true;
}

// Begin BFS
while !q.is_empty() {
let ((i, st), count) = q.pop_front().unwrap();
if st == ((1 << n) - 1) {
return count;
}
// If the path has not been visited
for j in &graph[i] {
let nst = st | (1 << *j);
if !vis[*j as usize][nst] {
q.push_back(((*j as usize, nst), count + 1));
vis[*j as usize][nst] = true;
}
}
}

-1
}
}
```

### **Go**

```go
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
use std::collections::VecDeque;

impl Solution {
#[allow(dead_code)]
pub fn shortest_path_length(graph: Vec<Vec<i32>>) -> i32 {
let n = graph.len();
let mut vis = vec![vec![false; 1 << n]; n];
let mut q = VecDeque::new();

// Initialize the queue
for i in 0..n {
q.push_back(((i, 1 << i), 0));
vis[i][1 << i] = true;
}

// Begin BFS
while !q.is_empty() {
let ((i, st), count) = q.pop_front().unwrap();
if st == ((1 << n) - 1) {
return count;
}
// If the path has not been visited
for j in &graph[i] {
let nst = st | (1 << *j);
if !vis[*j as usize][nst] {
q.push_back(((*j as usize, nst), count + 1));
vis[*j as usize][nst] = true;
}
}
}

-1
}
}