我是Rust的新手。我的代码如下:
use std::*;
fn DFS(A: i32, grid: &mut [[i32; 500]; 500], visited: &mut [i32; 500]) -> (usize, usize) {
let mut s = Vec::new();
s.push(A);
visited[A as usize] = 1;
let mut flag;
let mut max_height = 0;
let mut ans_vertex: usize = A as usize;
let mut x;
'outer: while let Some(top) = s.pop() {
s.push(top);
x = top as usize;
flag = 0;
'inner: for i in 1..500 {
if visited[grid[x][i] as usize] == 0 && grid[x][i] != 0 {
flag = 1;
s.push(grid[x][i]);
visited[grid[x][i] as usize] = 1;
break 'outer;
}
}
if s.len() > max_height {
max_height = s.len();
ans_vertex = s.pop() as usize;
}
if flag != 0 {
s.pop();
}
}
println!("{}, {}", ans_vertex, max_height);
return (ans_vertex, max_height);
}
fn fc(grid: &mut [[i32; 500]; 500]) {
for i in 1..500 {
for j in 1..500 {
grid[i][j] = 0;
}
}
grid[1][2] = 1;
grid[2][1] = 1;
grid[2][3] = 1;
grid[3][2] = 1;
grid[3][4] = 1;
grid[4][3] = 1;
}
fn main() {
let mut visited: [i32; 500] = [0; 500];
let mut grid: [[i32; 500]; 500] = [[0; 500]; 500];
fc(&mut grid);
let B = DFS(1, &mut grid, &mut visited);
println!("{}", B.0);
}
我已尝试将usize
更改为u32
和其他类型,但我没有得到任何结果。当我运行rustc newdia.rs
时,它会显示:
newdia.rs:26:17: 26:33 error: non-scalar cast: `core::option::Option<i32>` as `usize`
newdia.rs:26 ans_vertex = s.pop() as usize;
^~~~~~~~~~~~~~~~
error: aborting due to previous error
答案 0 :(得分:0)
Vec::pop()
会返回Option<T>
,因为如果Vec为空,则弹出窗口没有值。如果您确定在致电Vec::pop()
之前您的Vec包含至少1个值,则可以使用Option::unwrap()
,这会将您的Option<i32>
转换为i32
(如果{{{}则会发生恐慌1}}返回Vec::pop
,因为Vec是空的。)
None
您还可以选择使用ans_vertex = s.pop().unwrap() as usize;
或match
if let