//////////////////////////////////////////////////
// Find the shortest step number, no path to show
// left top is the end point
// right bottom is the start point
//
//
!!!!!!Warning!!!!!!
// The maze in sos.in must have an answer
// Otherwise the the prog. will always loop
//////////////////////////////////////////////////
#include<stdio.h>
int main(void)
{
int i,j,k;
int n;
// map matrix n*n
int x[30][30];// max map buff 30*30
int t,c;
FILE *in,*out;
in=fopen("sos.in","r");
out=fopen("sos.out","w");
fscanf(in,"%d",&n);// first line in sos.in to n
// raw data array sequence is form 1 to n
// but in C/C++, array index starts with 0
//Ini the map from sos.in
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
fscanf(in,"%d",&x[i][j]);
if(x[i][j]==1) x[i][j]=-1; //wall
-1
else x[i][j]=1000;
// walk path 1000.
}
// why 1000? bcs 30*30==900 <1000
x[0][0]=1;// set the first step number,
// not step sequence in the maze! It's end point.
c=n-1;
// reset the array sequence from 0 to n-1
/////////////////////////////////////////////////
//
Algorithm:
// An Iterator goes from up to down,
// and at the same time left to right in the maze.
// If the neighbor position can be walked
// and the {value+1} is smaller than self,
// set the self to {value+1} .
// When the Iterator goes to the start point
// (x[n-1,n-1]),the value of it
// is the answer to the ques.
.
/////////////////////////////////////////////////
while(x[c][c]==1000)
{
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
// if not the most left, left
if(i>0)
if(x[i-1][j]!=-1)
if((t=x[i-1][j]+1)<x[i][j])
x[i][j]=t;
// if not the most right, right
if(i<c)
if(x[i+1][j]!=-1)
if((t=x[i+1][j]+1)<x[i][j])
x[i][j]=t;
// if not the most up, up
if(j>0)
if(x[i][j-1]!=-1)
if((t=x[i][j-1]+1)<x[i][j])
x[i][j]=t;
// if not the most down, down
if(j<c)
if(x[i][j+1]!=-1)
if((t=x[i][j+1]+1)<x[i][j])
x[i][j]=t;
}
}
//Output the shortest steps
fprintf(out,"%d\n",x[c][c]);
//discard opened files
fclose(in);
fclose(out);
return 0;
}