use std::collections::VecDeque; fn main() { let (W, H): (i32, i32) = { let mut line: String = String::new(); std::io::stdin().read_line(&mut line).unwrap(); let mut iter = line.split_whitespace(); ( iter.next().unwrap().parse().unwrap(), iter.next().unwrap().parse().unwrap(), ) }; let mut map=vec![Vec::new();H as usize]; for i in 0..H{ let a: Vec = { let mut line: String = String::new(); std::io::stdin().read_line(&mut line).unwrap(); line.split_whitespace() .map(|x| x.parse().unwrap()) .collect() }; map[i as usize]=a; } let mut dp=vec![vec![vec![(1 as i64) <<60;12];W as usize];H as usize]; let mut q:VecDeque<(i32,i32,i32)>=VecDeque::new(); let dx: [i32; 4] = [-1, 0, 1, 0]; let dy: [i32; 4] = [0, -1, 0, 1]; for i in 0..11{ dp[0][0][i]=0; q.push_back((0,0,(i as i32))); } while q.len()>0{ let (x0,y0,a)=q.pop_front().unwrap(); for i in 0..4{ let x:i32 = x0 as i32 +dx[i]; let y:i32 = y0 as i32 +dy[i]; if 0<=x && xc) || (a>b && bdp[x0 as usize][y0 as usize][a as usize]+1{ dp[x as usize][y as usize][b as usize]=dp[x0 as usize][y0 as usize][a as usize]+1; q.push_back((x,y,b)) } } } } } let mut ans=1<<60; for i in 1..10{ let k =dp[H as usize-1][W as usize-1][i]; if ans>k{ ans=k; } } if (ans==1<<60){ println!("{}",-1); } else{ println!("{}",ans); } }