Last active
February 3, 2019 22:34
-
-
Save AnthonyMikh/d32380a2255409f201fd0a5b59dedb63 to your computer and use it in GitHub Desktop.
Решение задачи №154 от UniLecs (Тетрадь в клеточку - 2)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const BLANK: u8 = 0; | |
const PAINTED: u8 = 1; | |
///Возвращает сторону самого большого квадрата, | |
///который можно разместить в m, не накрывая закрашенных клеток, | |
///и количество таких квадратов. | |
fn count_max_squares<Row>(m: &[Row]) -> (usize, usize) | |
where | |
Row: AsRef<[u8]> | |
{ | |
use std::cmp::Ordering; | |
let side = m.len(); | |
assert!(side != 0); | |
let mut max_sq = vec![vec![0; side]; side]; | |
let mut max_side = 0; | |
let mut max_count = 0; | |
//Заполняем первую строку | |
for col in 0..side { | |
if m[0].as_ref()[col] == BLANK { | |
max_side = 1; | |
max_count += 1; | |
max_sq[0][col] = 1; | |
} else { | |
max_sq[0][col] = 0; | |
} | |
} | |
//Заполняем первый столбец | |
for row in 1..side { | |
if m[row].as_ref()[0] == BLANK { | |
max_side = 1; | |
max_count += 1; | |
max_sq[row][0] = 1; | |
} else { | |
max_sq[row][0] = 0; | |
} | |
} | |
for row in 1..side { | |
for col in 1..side { | |
if m[row].as_ref()[col] == PAINTED { | |
max_sq[row][col] = 0; | |
continue | |
} | |
let left = max_sq[row][col - 1]; | |
let top = max_sq[row - 1][col]; | |
let corner = max_sq[row - 1][col - 1]; | |
let current = left.min(top).min(corner) + 1; | |
match current.cmp(&max_side) { | |
Ordering::Less => (), | |
Ordering::Equal => { | |
max_count += 1; | |
}, | |
Ordering::Greater => { | |
max_side = current; | |
max_count = 1; | |
}, | |
} | |
max_sq[row][col] = current; | |
} | |
} | |
(max_side, max_count) | |
} | |
fn main() { | |
use PAINTED as P; | |
assert!(P != 0); | |
let m = [ | |
[P, 0, 0, 0, 0, P], | |
[0, P, 0, 0, 0, 0], | |
[P, 0, 0, 0, 0, 0], | |
[0, 0, P, 0, 0, 0], | |
[0, 0, 0, 0, P, 0], | |
[0, 0, P, 0, 0, 0], | |
]; | |
println!("{:?}", count_max_squares(&m)); //(3, 2) | |
let m = [ | |
[0, 0, 0], | |
[0, 0, P], | |
[0, 0, 0] | |
]; | |
println!("{:?}", count_max_squares(&m)); //(2, 2) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Playground v2: https://play.rust-lang.org/?gist=14e84ca1c10fafb7262e672d1c23f429