using System; using System.Collections.Generic; namespace Csharp { class Program { class Elem { public int R, C, HadDestructed; public Elem(int r, int c, int h) { R = r; C = c; HadDestructed = h; } } static int N, M; static string[] Map = new string[1000]; static int[,,] Dists = new int[1000, 1000, 2]; static void Main(string[] args) { var inputs = Console.ReadLine().Split(); N = Convert.ToInt32(inputs[0]); M = Convert.ToInt32(inputs[1]); for (int i = 0; i < N; ++i) Map[i] = Console.ReadLine(); Console.Write(bfs()); } static int bfs() { Queue<Elem> q = new Queue<Elem>(); int[] dr = { -1, 1, 0, 0 }; int[] dc = { 0, 0, -1, 1 }; Dists[0, 0, 0] = 1; q.Enqueue( new Elem(0, 0, 0) ); while (q.Count != 0) { Elem elem = q.Dequeue(); if (elem.R == (N - 1) && elem.C == (M - 1)) return Dists[elem.R, elem.C, elem.HadDestructed]; for (int i = 0; i < 4; ++i) { int nr = elem.R + dr[i]; int nc = elem.C + dc[i]; if (nr < 0 || nr >= N || nc < 0 || nc >= M) continue; else if (Dists[nr, nc, elem.HadDestructed] != 0) continue; if (Map[nr][nc] == '0') { Dists[nr, nc, elem.HadDestructed] = Dists[elem.R, elem.C, elem.HadDestructed] + 1; q.Enqueue(new Elem(nr, nc, elem.HadDestructed)); } else if (elem.HadDestructed == 0) { Dists[nr, nc, 1] = Dists[elem.R, elem.C, elem.HadDestructed] + 1; q.Enqueue(new Elem(nr, nc, 1)); } } } return -1; } } } |