aoc22/day08/src/main1.rs

60 lines
1.7 KiB
Rust
Raw Normal View History

2024-03-11 00:56:04 -05:00
use std::env;
use std::fs;
fn main() {
let input = fs::read_to_string(&env::args().nth(1).unwrap()).unwrap();
let forest: Vec<Vec<i8>> = input.lines()
.map(|line| line.chars()
.map(|c| c.to_digit(10).unwrap() as i8).collect())
.collect();
let nrows = forest.len();
let ncols = forest[0].len();
let min_from_left: Vec<Vec<i8>> = forest.iter()
.map(|row| row.iter()
.scan(-1, |h, &tree| {
let old = *h; *h = i8::max(*h as i8, tree); Some(old)
})
.collect())
.collect();
let min_from_right: Vec<Vec<i8>> = forest.iter()
.map(|row: &Vec<i8>| row.iter()
.rev()
.scan(-1, |h, &tree| {
let old = *h; *h = i8::max(*h as i8, tree); Some(old)
})
.collect::<Vec<i8>>().iter()
.rev().map(|x| *x)
.collect())
.collect();
let mut min_from_top: Vec<Vec<i8>> = vec![vec![-1; ncols]; nrows];
for c in 0..ncols {
for r in 1..nrows {
min_from_top[r][c] = i8::max(min_from_top[r-1][c], forest[r-1][c]);
}
}
let mut min_from_bot: Vec<Vec<i8>> = vec![vec![-1; ncols]; nrows];
for c in 0..ncols {
for r in (0..nrows-1).rev() {
min_from_bot[r][c] = i8::max(min_from_bot[r+1][c], forest[r+1][c]);
}
}
let mut sum = 0;
for r in 0..nrows {
for c in 0..ncols {
if forest[r][c] > min_from_left[r][c]
|| forest[r][c] > min_from_right[r][c]
|| forest[r][c] > min_from_top[r][c]
|| forest[r][c] > min_from_bot[r][c] {
sum += 1;
}
}
}
println!("{:?}", sum);
}