using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Globalization;
using System.Xml.Linq;
using System.Data;
class GridPath {
    public static List<int> Find(bool[,] blocked,int start,int goal) {
        int rows=blocked.GetLength(0),cols=blocked.GetLength(1),size=rows*cols;
        if(start<0 || goal<0 || start>=size || goal>=size)throw new ArgumentOutOfRangeException();
        if(blocked[start/cols,start%cols] || blocked[goal/cols,goal%cols])return new List<int>();
        int[] parent=Enumerable.Repeat(-1,size).ToArray();var queue=new Queue<int>();
        parent[start]=start;queue.Enqueue(start);int[] dr={-1,0,1,0},dc={0,1,0,-1};
        while(queue.Count>0) {
            int current=queue.Dequeue();if(current==goal)break;
            for(int k=0;k<4;k++) {
                int r=current/cols+dr[k],c=current%cols+dc[k];
                if(r<0 || c<0 || r>=rows || c>=cols || blocked[r,c])continue;
                int next=r*cols+c;if(parent[next]!=-1)continue;parent[next]=current;queue.Enqueue(next);
            }
        }
        var result=new List<int>();if(parent[goal]==-1)return result;
        for(int at=goal;;at=parent[at]) {result.Add(at);if(at==start)break;}
        result.Reverse();return result;
    }
}
class Program {
    static void Main() {
        var grid=new bool[5,5];Console.WriteLine(GridPath.Find(grid,0,24).Count-1);
        grid[0,1]=true;grid[1,0]=true;Console.WriteLine(GridPath.Find(grid,0,24).Count);
        Console.WriteLine(GridPath.Find(new bool[1,1],0,0).Count);
        var closed=new bool[1,1];closed[0,0]=true;Console.WriteLine(GridPath.Find(closed,0,0).Count);
    }
}
