use std::env; use std::fs; fn main() { let input = fs::read_to_string(&env::args().nth(1).unwrap()).unwrap(); let forest: Vec> = 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> = 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> = forest.iter() .map(|row: &Vec| row.iter() .rev() .scan(-1, |h, &tree| { let old = *h; *h = i8::max(*h as i8, tree); Some(old) }) .collect::>().iter() .rev().map(|x| *x) .collect()) .collect(); let mut min_from_top: Vec> = 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![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); }