solution accepted
This commit is contained in:
parent
5a9634eb5b
commit
72bb226f88
4 changed files with 75 additions and 0 deletions
1
.gitignore
vendored
1
.gitignore
vendored
|
@ -1 +1,2 @@
|
|||
*/target/
|
||||
*/Cargo.lock
|
||||
|
|
7
spiral_matrix/Cargo.lock
generated
Normal file
7
spiral_matrix/Cargo.lock
generated
Normal file
|
@ -0,0 +1,7 @@
|
|||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 3
|
||||
|
||||
[[package]]
|
||||
name = "spiral_matrix"
|
||||
version = "0.1.0"
|
8
where_will_the_ball_fall/Cargo.toml
Normal file
8
where_will_the_ball_fall/Cargo.toml
Normal file
|
@ -0,0 +1,8 @@
|
|||
[package]
|
||||
name = "where_will_the_ball_fall"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
59
where_will_the_ball_fall/src/main.rs
Normal file
59
where_will_the_ball_fall/src/main.rs
Normal file
|
@ -0,0 +1,59 @@
|
|||
fn find_ball(grid: Vec<Vec<i32>>) -> Vec<i32> {
|
||||
let balls = grid[0].len();
|
||||
let mut res = vec![-1; balls];
|
||||
|
||||
for ball in 0..balls {
|
||||
let mut pos = ball;
|
||||
let mut stuck = false;
|
||||
for row in grid.iter() {
|
||||
if let Some(npos) = can_fall(pos, row) {
|
||||
pos = npos as usize;
|
||||
} else {
|
||||
stuck = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if !stuck {
|
||||
res[ball] = pos as i32;
|
||||
}
|
||||
}
|
||||
|
||||
res
|
||||
}
|
||||
|
||||
fn can_fall(pos: usize, row: &[i32]) -> Option<i32> {
|
||||
//
|
||||
let mut res = None;
|
||||
let len = row.len();
|
||||
match row[pos] {
|
||||
1 => {
|
||||
if pos < len.saturating_sub(1) {
|
||||
let right = row[pos + 1];
|
||||
if right > 0 {
|
||||
res = Some(pos as i32 + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if pos > 0 {
|
||||
let left = row[pos - 1];
|
||||
if left < 0 {
|
||||
res = Some(pos as i32 - 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
res
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let res = find_ball(vec![
|
||||
vec![1, 1, 1, -1, -1],
|
||||
vec![1, 1, 1, -1, -1],
|
||||
vec![-1, -1, -1, 1, 1],
|
||||
vec![1, 1, 1, 1, -1],
|
||||
vec![-1, -1, -1, -1, -1],
|
||||
]);
|
||||
|
||||
dbg!(res);
|
||||
}
|
Loading…
Reference in a new issue