The C++ code you provided is not completely straightforward to translate directly to Rust due to differences in language idioms and libraries. However, we can attempt to translate the logic of this C++ program to Rust step by step. Below, I provide a Rust translation of the C++ code, keeping the structure as close as possible. Please note that in Rust, all values are immutable by default, and mutable values are explicitly marked with mut. Additionally, error handling in Rust is explicit and type conversion is more strict.
use std::io::{self, prelude::*, BufReader};
use std::collections::VecDeque;
const DI_ADJ: [i32; 4] = [-1, 0, 1, 0];
const DJ_ADJ: [i32; 4] = [0, -1, 0, 1];
const DI_DIAG: [i32; 8] = [0, 0, -1, 1, -1, -1, 1, 1];
const DJ_DIAG: [i32; 8] = [-1, 1, 0, 0, -1, 1, 1, -1];
fn in_grid(i: isize, j: isize, n: isize, m: isize) -> bool {
i >= 0 && i < n && j >= 0 && j < m
}
fn on_border(i: isize, j: isize, n: isize, m: isize) -> bool {
i == 0 || i == n - 1 || j == 0 || j == m - 1
}
fn get_reach(i: isize, j: isize, min_val: i32, n: isize, m: isize, reachable: &mut Vec<Vec<bool>>, dist: &Vec<Vec<i32>>, a: &Vec<String>) {
if !in_grid(i, j, n, m) || reachable[i as usize][j as usize] || dist[i as usize][j as usize] < min_val || a[i as usize].chars().nth(j as usize) == Some('#') {
return;
}
reachable[i as usize][j as usize] = true;
for dir in 0..4 {
get_reach(i + DI_ADJ[dir] as isize, j + DJ_ADJ[dir] as isize, min_val, n, m, reachable, dist, a);
}
}
fn reach_border(i: isize, j: isize, n: isize, m: isize, reachable: &Vec<Vec<bool>>, island_vis: &mut Vec<Vec<bool>>) -> bool {
if !in_grid(i, j, n, m) || reachable[i as usize][j as usize] || island_vis[i as usize][j as usize] {
return false;
}
if on_border(i, j, n, m) {
return true;
}
island_vis[i as usize][j as usize] = true;
let mut ok = false;
for dir in 0..8 {
ok |= reach_border(i + DI_DIAG[dir] as isize, j + DJ_DIAG[dir] as isize, n, m, reachable, island_vis);
}
ok
}
fn exists_round_trip(x: isize, y: isize, min_val: i32, n: isize, m: isize, islandi: isize, islandj: isize, a: &Vec<String>, dist: &Vec<Vec<i32>>) -> bool {
let mut reachable: Vec<Vec<bool>> = vec![vec![false; m as usize]; n as usize];
let mut island_vis: Vec<Vec<bool>> = vec![vec![false; m as usize]; n as usize];
// Get all valid cells you can reach from (x, y)
get_reach(x, y, min_val, n, m, &mut reachable, dist, a);
// Check if the valid cells you can reach from (x, y) blocks the island from the border
!reach_border(islandi, islandj, n, m, &reachable, &mut island_vis)
}
fn main() {
let stdin = io::stdin();
let reader = BufReader::new(stdin);
let mut lines = reader.lines().map(|l| l.unwrap());
let first_line = lines.next().unwrap();
let parts: Vec<&str> = first_line.split_whitespace().collect();
let n: isize = parts[0].parse().unwrap();
let m: isize = parts[1].parse().unwrap();
let q: usize = parts[2].parse().unwrap();
let mut a: Vec<String> = Vec::with_capacity(n as usize);
let mut dist: Vec<Vec<i32>> = vec![vec![i32::MAX; m as usize]; n as usize];
let mut islandi = 0;
let mut islandj = 0;
let mut bfs_queue: VecDeque<(isize, isize)> = VecDeque::new();
for i in 0..n {
let line = lines.next().unwrap();
a.push(line.clone());
for (j, c) in line.chars().enumerate() {
if c == 'v' {
dist[i as usize][j] = 0;
bfs_queue.push_back((i, j as isize));
}
if c == '#' {
islandi = i;
islandj = j as isize;
}
}
}
// Multisource BFS to find min distance to volcano
while let Some((i, j)) = bfs_queue.pop_front() {
for dir in 0..4 {
let ni = i + DI_ADJ[dir] as isize;
let nj = j + DJ_ADJ[dir] as isize;
if in_grid(ni, nj, n, m) && dist[i as usize][j as usize] + 1 < dist[ni as usize][nj as usize] {
dist[ni as usize][nj as usize] = dist[i as usize][j as usize] + 1;
bfs_queue.push_back((ni, nj));
}
}
}
for _ in 0..q {
let line = lines.next().unwrap();
let parts: Vec<&str> = line.split_whitespace().collect();
let mut x: isize = parts[0].parse().unwrap();
let mut y: isize = parts[1].parse().unwrap();
x -= 1;
y -= 1;
let mut l = 0;
let mut h = n + m;
while l < h {
let m = (l + h + 1) / 2;
if exists_round_trip(x, y, m as i32, n, m, islandi, islandj, &a, &dist) {
l = m;
} else {
h = m - 1;
}
}
println!("{}", l);
}
}
Some key points to consider:
- Instead of using
#include <bits/stdc++.h>, which is not available in Rust, we import necessary modules on top of the Rust file.
- Rust does not have a direct equivalent of
std::vector; instead, it uses Vec<T> for dynamic arrays. Also, unlike C++, Rust requires explicit handling of mutability (mut keyword).
std::queue in C++ is replaced with std::collections::VecDeque in Rust.
- The
prelude::* import is used to bring common types and traits into scope, such as BufReader and Read.
- Rust emphasizes the use of
Result types for error handling, which require dealing with potentially fallible operations (like parsing) explicitly.
- Rust arrays (
[i32; 4] and [i32; 8]) are used to store constant arrays for adjacency and diagonal directions.
- Rust uses snake_case for naming conventions, as opposed to lowerCamelCase commonly found in C++.
- Tuple destructuring is used in the
Some((i, j)) pattern matching within the while loop.
- The range-based for loops in C++ have been replaced with iterator-based
for loops in Rust.
- Variables and values need to be explicitly cast or parsed into appropriate types for arithmetic or indexing operations.
This Rust translation attempts to maintain a similar program structure and should exhibit the same behavior as the original C++ code. However, keep in mind that due to differences between C++ and Rust, particularly regarding ownership and borrowing, some adaptations must be made when translating between the two languages.