1861-rotating-the-box.rs (3063B)
1/// 1861. Rotating the Box (Medium) 2/// 3/// You are given an m x n matrix of characters box representing a side-view of 4/// a box. Each cell of the box is one of the following: 5/// 6/// * A stone '#' 7/// * A stationary obstacle '*' 8/// * Empty '.' 9/// 10/// The box is rotated *90 degrees clockwise*, causing some of the stones to 11/// fall due to gravity. Each stone falls down until it lands on an obstacle, 12/// another stone, or the bottom of the box. Gravity *does not* affect the 13/// obstacles' positions, and the inertia from the box's rotation *does not 14/// *affect the stones' horizontal positions. 15/// 16/// It is *guaranteed* that each stone in box rests on an obstacle, another 17/// stone, or the bottom of the box. 18/// 19/// Return an n x m matrix representing the box after the rotation described 20/// above. 21/// 22/// *Example 1:* 23/// 24/// *Input:* box = [["#",".","#"]] 25/// *Output:* [["."], 26/// ["#"], 27/// ["#"]] 28/// 29/// *Example 2:* 30/// 31/// *Input:* box = [["#",".","*","."], 32/// ["#","#","*","."]] 33/// *Output:* [["#","."], 34/// ["#","#"], 35/// ["*","*"], 36/// [".","."]] 37/// 38/// *Example 3:* 39/// 40/// *Input:* box = [["#","#","*",".","*","."], 41/// ["#","#","#","*",".","."], 42/// ["#","#","#",".","#","."]] 43/// *Output:* [[".","#","#"], 44/// [".","#","#"], 45/// ["#","#","*"], 46/// ["#","*","."], 47/// ["#",".","*"], 48/// ["#",".","."]] 49/// 50/// *Constraints:* 51/// 52/// * m == box.length 53/// * n == box[i].length 54/// * 1 <= m, n <= 500 55/// * box[i][j] is either '#', '*', or '.'. 56/// 57use leetcode::*; 58 59struct Solution {} 60 61impl Solution { 62 pub fn rotate_the_box(in_box: Vec<Vec<char>>) -> Vec<Vec<char>> { 63 let n = in_box.len(); 64 let m = in_box[0].len(); 65 let mut out_box = vec![vec!['.'; n]; m]; 66 for x in (0..n).rev() { 67 let mut last = m - 1; 68 for y in (0..m).rev() { 69 let c = in_box[n - 1 - x][y]; 70 if c == '*' { 71 out_box[y][x] = '*'; 72 if y > 0 { 73 last = y - 1; 74 } 75 } else if c == '#' { 76 out_box[last][x] = '#'; 77 last = last.saturating_sub(1); 78 } 79 } 80 } 81 out_box 82 } 83} 84 85pub fn main() { 86 println!("{:?}", Solution::rotate_the_box(arg_into(1))); 87} 88 89#[cfg(test)] 90mod tests { 91 use crate::Solution; 92 use leetcode::vvc; 93 94 #[test] 95 fn test() { 96 assert_eq!( 97 Solution::rotate_the_box(vvc("[[#,.,#]]")), 98 vvc("[[.],[#],[#]]") 99 ); 100 assert_eq!( 101 Solution::rotate_the_box(vvc("[[#,.,*,.],[#,#,*,.]]")), 102 vvc("[[#,.],[#,#],[*,*],[.,.]]") 103 ); 104 assert_eq!( 105 Solution::rotate_the_box(vvc("[[#,#,*,.,*,.],[#,#,#,*,.,.],[#,#,#,.,#,.]]")), 106 vvc("[[.,#,#],[.,#,#],[#,#,*],[#,*,.],[#,.,*],[#,.,.]]") 107 ) 108 } 109}