有一个5*5的网格,其中恰好有一个格子是空的,其他格子各有一个字母。一共有4种指令:A, B, L, R,分别表示把空格上、下、左、右的相邻字母移到空格中。输入初始网格和指令序列(以数字0结束),输出指令执行完毕后的网格。如果有非法指令,应输出“This puzzle has no final configuration.”,例如,图3-5中执行ARRBBL0后,效果如图3-6所示。
解法
use std::io;fn main() {let mut grid: Vec<Vec<char>> = vec![];for _i in 0..5 {let mut buf = String::new();io::stdin().read_line(&mut buf).unwrap();let cs = buf.trim().chars().collect();grid.push(cs);}println!("{:#?}", grid);let mut buf = String::new();io::stdin().read_line(&mut buf).unwrap();let cmds = buf.trim();println!("{}", cmds);let mut kong = (0, 0);for i in 0..5 {for j in 0..5 {if grid[i][j] == ' ' {kong = (i, j);break;}}}for i in cmds.chars() {match i {'a' => {if kong.0 < 1 {panic!("This puzzle has no final configuration");}let c = grid[kong.0 - 1][kong.1];grid[kong.0][kong.1] = c;grid[kong.0 - 1][kong.1] = ' ';kong = (kong.0 - 1, kong.1);}'b' => {if kong.0 >= 4 {panic!("This puzzle has no final configuration");}let c = grid[kong.0 + 1][kong.1];grid[kong.0][kong.1] = c;grid[kong.0 + 1][kong.1] = ' ';kong = (kong.0 + 1, kong.1);}'l' => {if kong.1 < 1 {panic!("This puzzle has no final configuration");}let c = grid[kong.0][kong.1 - 1];grid[kong.0][kong.1] = c;grid[kong.0][kong.1 - 1] = ' ';kong = (kong.0, kong.1 - 1);}'r' => {if kong.1 >= 4 {panic!("This puzzle has no final configuration");}let c = grid[kong.0][kong.1 + 1];grid[kong.0][kong.1] = c;grid[kong.0][kong.1 + 1] = ' ';kong = (kong.0, kong.1 + 1);}'0' => {break;}_ => {panic!("This puzzle has no final configuration");}}}println!("{:#?}", grid);
}