From e00fa116c51e728e341e48e4c5f9f09cf4d416fc Mon Sep 17 00:00:00 2001 From: stale Date: Sun, 5 Jun 2022 20:43:32 -0300 Subject: code cleanup, floodfill algo changed to iterative --- src/minesweeper.rs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) (limited to 'src/minesweeper.rs') diff --git a/src/minesweeper.rs b/src/minesweeper.rs index 013e441..288847e 100644 --- a/src/minesweeper.rs +++ b/src/minesweeper.rs @@ -5,7 +5,6 @@ use std::{ use rand::{ thread_rng, Rng, distributions::Uniform }; use serde::Serialize; -const FLOOD_MAX_DEPTH: usize = 64; const HIDDEN_BIT: u8 = 1 << 7; pub const FLAGGED_BIT: u8 = 1 << 6; const CORRECT_BIT: u8 = 1 << 5; // grading for a rightly flagged mine @@ -187,25 +186,26 @@ impl Board { (x < self.width.get() && y < self.height.get()).then(|| (x,y)) } else { None } } - pub fn flood_reveal(&mut self, pos: (usize,usize), depth: usize) { - if depth > 0 { + pub fn flood_reveal(&mut self, pos: (usize,usize)) { + let mut queue = vec![pos]; + while let Some(pos) = queue.pop() { if let Some(off) = self.pos_to_off(pos) { let c = &mut self.data[off]; if *c & HIDDEN_BIT > 0 { *c &= !(HIDDEN_BIT | FLAGGED_BIT); self.hidden_tiles -= 1; - if *c > 0 { return } + if *c > 0 { continue; } drop(c); - self.neighs(pos).map(|n| n.iter().for_each(|pos| { - self.flood_reveal(*pos, depth - 1); - })); + if let Some(mut adj) = self.neighs(pos) { + queue.append(&mut adj); + } } } } } pub fn reveal(mut self, pos: (usize,usize)) -> MoveResult { if let Some(off) = self.pos_to_off(pos) { - self.flood_reveal(pos, FLOOD_MAX_DEPTH); + self.flood_reveal(pos); let c = self.data[off]; MoveResult { 0: self, 1: (c & !(FLAGGED_BIT | CORRECT_BIT)) == TILE_NUMBITS } } else { -- cgit v1.2.3