典型的bfs。
代码如下:
#define MAXN 55
#define INF 0x7fffffff
#include<stdio.h>
#include<string.h>
int T, N, M, Sr,Sc,Er,Ec, min;
char s[MAXN][MAXN], vis[MAXN][MAXN];
int q[MAXN*MAXN], dis[MAXN][MAXN];
int dx[4] = {0,0,-1,1};
int dy[4] = {1,-1,0,0};
void solve(int x, int y)
{
min = INF;
memset(vis,0,sizeof(vis));
memset(dis,0,sizeof(dis));
int front = 0, rear = 0;
int u = (x-1)*M + y;
vis[x][y] = 1; dis[x][y] = 0;
q[rear++] = u;
while(front < rear)
{
u = q[front++];//printf("...u==%d\n",u);
y = u%M;
if(y==0) y = M;
x = (u-y)/M + 1;// printf("...x=%d y=%d\n",x,y);
for(int i = 0; i < 4; i ++)
{
int nx = x+dx[i], ny = y+dy[i];
if(nx>0 && nx<N+1 && ny>0 && ny<M+1 )
{
if('1'-s[nx][ny] && !vis[nx][ny])
{
int v = (nx-1)*M + ny;//printf("v==%d\n",v);
q[rear++] = v;
vis[nx][ny] = 1;
dis[nx][ny] = dis[x][y] + 1;
}
}
if(u == (Er-1)*M+Ec && dis[x][y] < min) min = dis[x][y];
}
}
if(min == INF)printf("No Path.\n");
else printf("%d\n",min);
}
void input()
{
while(scanf("%d",&T) == 1)
while(T --)
{
scanf("%d%d",&N, &M);
scanf("%d%d%d%d",&Sr,&Sc,&Er,&Ec);
for(int i = 1; i <= N; i ++)
scanf("%s",s[i]+1);
solve(Sr,Sc);
}
}
int main()
{
input();
return 0;
}