using System; using System.Collections.Generic; using System.Text; using System.Linq; class Program { public void Proc() { Reader.IsDebug = false; int[] inpt = Reader.GetInt(); int width = inpt[0]; int height = inpt[1]; int[,] map = new int[height, width]; for(int i=0; i task = new Queue(); task.Enqueue(new TaskItem(0,0,-1,0)); task.Enqueue(new TaskItem(0,0,100,0)); Dictionary[,] step = new Dictionary[height, width]; while (task.Count > 0) { TaskItem t = task.Dequeue(); if(step[t.Y, t.X] == null) { step[t.Y, t.X] = new Dictionary(); } if(step[t.Y, t.X].ContainsKey(t.Prev)) { if(step[t.Y, t.X][t.Prev] <= t.NextStep) { continue; } else { step[t.Y, t.X][t.Prev] = t.NextStep; } } else { step[t.Y, t.X].Add(t.Prev, t.NextStep); } if(t.X == width - 1 && t.Y == height - 1) { continue; } List nextPosList = new List(); if(t.Y > 0) { nextPosList.Add(new int[]{t.Y-1, t.X}); } if(t.Y < height - 1) { nextPosList.Add(new int[]{t.Y+1, t.X}); } if(t.X > 0) { nextPosList.Add(new int[]{t.Y, t.X - 1}); } if(t.X < width - 1) { nextPosList.Add(new int[]{t.Y, t.X + 1}); } int nowLen = map[t.Y, t.X]; nextPosList.ForEach((a)=>{ int nextY = a[0]; int nextX = a[1]; int nextLen = map[nextY, nextX]; if(nowLen == nextLen || t.Prev == nextLen) { return; } if(t.Prev > nowLen && nowLen > nextLen) { return; } if(t.Prev < nowLen && nowLen < nextLen) { return; } TaskItem newTask = new TaskItem(nextX, nextY, nowLen, t.NextStep + 1); task.Enqueue(newTask); }); } int ans = 0; if(step[height-1, width-1] == null) { ans = -1; } else { ans = step[height-1, width-1].Values.Min(); } Console.WriteLine(ans); } public class TaskItem { public int X; public int Y; public int Prev; public int NextStep; public TaskItem(int x, int y, int prev, int nextstep) { this.X = x; this.Y = y; this.Prev = prev; this.NextStep = nextstep; } } public class CellState { public int Prev; public int Step; public CellState(int prev, int step) { this.Prev = prev; this.Step = step; } } public class Reader { public static bool IsDebug = true; private static String PlainInput = @" 3 3 5 4 1 6 6 9 2 8 8 "; private static System.IO.StringReader Sr = null; public static string ReadLine() { if (IsDebug) { if (Sr == null) { Sr = new System.IO.StringReader(PlainInput.Trim()); } return Sr.ReadLine(); } else { return Console.ReadLine(); } } public static int[] GetInt(char delimiter = ' ', bool trim = false) { string inptStr = ReadLine(); if (trim) { inptStr = inptStr.Trim(); } string[] inpt = inptStr.Split(delimiter); int[] ret = new int[inpt.Length]; for (int i = 0; i < inpt.Length; i++) { ret[i] = int.Parse(inpt[i]); } return ret; } } static void Main() { Program prg = new Program(); prg.Proc(); } }