现在的位置: 首页 > 综合 > 正文

最少步数(BFS)

2017年11月22日 ⁄ 综合 ⁄ 共 930字 ⁄ 字号 评论关闭

又是简单的搜索题,不过我的代码能力太差了,一道题,只是写代码就花了哥很长时间去调试,~\(≧▽≦)/~啦啦啦

http://59.69.128.200/JudgeOnline/problem.php?pid=58

#include <iostream>
#include<cstdio>
#include <queue>
#include<string.h>
using namespace std;
int si,sj,ei,ej;
int dir[][2]={{0,1},{0,-1},{1,0},{-1,0},{1,1},{1,-1},{-1,1},{-1,-1}};  
struct node{
	int x,y,num;
	node(int xx=0,int yy=0,int nn=0){x=xx;y=yy;num=nn;}
};
int bfs(int mat[][9])
{
	int bu;
	queue<node> Q;
	node fr;
	mat[si][sj]=1;
	Q.push(node(si,sj,0));
	while(!Q.empty())
	{
		fr=Q.front();
		Q.pop();
		if(fr.x==ei&&fr.y==ej)
			return fr.num;
		for(int i=0;i<4;i++)
		{
			int ii=fr.x+dir[i][0],jj=fr.y+dir[i][1];
			if(ii>=0&&jj>=0&&ii<9&&jj<9&&mat[ii][jj]==0)
			{
				Q.push(node(ii,jj,fr.num+1));
				mat[ii][jj]=1;
			}
		}		
	}
}
int main()
{
	int n;
	scanf("%d",&n);
	while(n--)
	{
		int mat[9][9]={ 
			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};
			scanf("%d%d%d%d",&si,&sj,&ei,&ej);
			printf("%d\n",bfs(mat));
	}
}

【上篇】
【下篇】

抱歉!评论已关闭.