use std::io; fn valid(map: &[Vec], x: i32, y: i32) -> bool { if x < 0 { return false; } if y < 0 { return false; } let uy: usize = y.try_into().unwrap(); if uy >= map.len() { return false; } let ux: usize = x.try_into().unwrap(); if ux >= map[uy].len() { return false; } true } fn is_paper(map: &[Vec], x: i32, y: i32) -> bool { if valid(map, x, y) { let uy: usize = y.try_into().unwrap(); let ux: usize = x.try_into().unwrap(); return map[uy][ux] == '@'; } false } fn adjacent(map: &[Vec], x: i32, y: i32) -> usize { let mut count = 0; for dx in -1..=1 { if is_paper(map, x + dx, y - 1) { count += 1; } if is_paper(map, x + dx, y + 1) { count += 1; } } if is_paper(map, x - 1, y) { count += 1; } if is_paper(map, x + 1, y) { count += 1; } count } fn main() { let mut map: Vec> = Vec::new(); loop { let mut buffer = String::new(); let bytes = io::stdin().read_line(&mut buffer).unwrap(); if bytes == 0 { break; } map.push(buffer.trim_end().chars().collect()); } let mut total = 0; for y in 0..map.len() { for x in 0..map[y].len() { if is_paper(&map, x.try_into().unwrap(), y.try_into().unwrap()) && adjacent(&map, x.try_into().unwrap(), y.try_into().unwrap()) < 4 { total += 1; } } } println!("{}", total); let mut total2 = 0; loop { total = 0; let mut next = map.clone(); for y in 0..map.len() { for x in 0..map[y].len() { if is_paper(&map, x.try_into().unwrap(), y.try_into().unwrap()) && adjacent(&map, x.try_into().unwrap(), y.try_into().unwrap()) < 4 { total += 1; next[y][x] = 'x'; } } } if total == 0 { break; } map = next; total2 += total; } println!("{}", total2); }