NYOJ-58:最少步数

/*BFS*/
#include
#include
#include
#include
using namespace std;
#define N 9
typedef struct
{
	int dir,i,j,cnt;
}Node;
int dir[4][2] = {{-1,0},{0,1},{1,0},{0,-1}};
int si,sj,ei,ej;
int mp[N][N] = 
{
	{1,1,1,1,1,1,1,1,1},
	{1,0,0,1,0,0,1,0,1},
	{1,0,0,1,1,0,0,0,1},
	{1,0,1,0,1,1,0,1,1},
	{1,0,0,0,0,1,0,0,1},
	{1,1,0,1,0,1,0,0,1},
	{1,1,0,1,0,1,0,0,1},
	{1,1,0,1,0,0,0,0,1},
	{1,1,1,1,1,1,1,1,1}
};
int vis[N][N];
int bfs()
{
	queue Q;
	Node tmp,p;
	p.i = si;	p.j = sj;
	p.cnt = 0;
	memset(vis,0,sizeof(vis));
	vis[si][sj] = 1;
	Q.push(p);
	while(!Q.empty())
	{
		p = Q.front();
		Q.pop();
		if (p.i == ei && p.j == ej)
			return p.cnt;
		int di=0;
		while(di<4)
		{
			tmp.i = p.i + dir[di][0];	tmp.j = p.j + dir[di][1];
			tmp.cnt = p.cnt + 1;
			if(tmp.i>=0 && tmp.i<=8 && tmp.j>=0 && tmp.j<=8 &&!vis[tmp.i][tmp.j] && !mp[tmp.i][tmp.j] )
			{
				Q.push(tmp);
				vis[tmp.i][tmp.j] = 1;
			}
			di++;
		}
	}
	return -1;
}
int main()
{
	int t;
	cin>>t;
	while(t--)
	{
		scanf("%d%d%d%d",&si,&sj,&ei,&ej);
		printf("%d\n",bfs());
	}
	return 0;
}

你可能感兴趣的:(BFS和DFS)