POJ1915(完全的模板题)
#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
int dir[8][2]={{-2,-1},{-1,-2},{1,2},{2,1},{1,-2},{2,-1},{-1,2},{-2,1}};
int visit[305][305],times;
struct point
{
int x,y;
};
queue<point> que;
void bfs(point stat,point ends,int n)
{
int i,que_size;
point head,next;
memset(visit,0,sizeof(visit));
times = 0;
while(!que.empty())
que.pop();
visit[stat.x][stat.y] = 1;
que.push(stat);
while(!que.empty())
{
que_size = que.size();
while(que_size--)
{
head = que.front();
que.pop();
if(head.x == ends.x&&head.y == ends.y)
return ;
for(i = 0;i < 8;i++)
{
next.x = head.x + dir[i][0];
next.y = head.y + dir[i][1];
if(next.x >= 0&&next.y >= 0&&next.x < n&&next.y < n&&!visit[next.x][next.y])
{
visit[next.x][next.y] = 1;
que.push(next);
}
}
}
times++;
}
}
int main()
{
int n;
cin >> n;
while(n--)
{
point stat,ends;
int m;
cin >> m;
cin >> stat.x >> stat.y;
cin >> ends.x >> ends.y;
if(stat.x == ends.x&&stat.y == ends.y) cout << '0' << endl;
else
{
bfs(stat,ends,m);
cout << times << endl;
}
}
return 0;
}
HDU1242(这个做法用的是邻接矩阵存储图,时间代价为O(n*n))
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
#define INF 1000000
using namespace std;
struct point //表示到某个方格时的状态
{
int x,y; //方格的位置
int step; //走到当前位置所进行的步数
int time; //走到当前位置所花的时间
};
queue<point> Q; //队列中的街道为当前ANGEL朋友所处的位置
int ax,ay,n,m; //n,m代表监狱的大小,ax,ay代表ANGLE的位置
char map[205][205]; //存储地图
int mintime[205][205],dir[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
//mintime表示走到每个位置所需的最小时间
int bfs(point s) //从位置S开始进行BFS搜索
{
int i;
Q.push(s);
point hd;
while(!Q.empty())
{
hd = Q.front(); Q.pop();
for(i = 0;i <4;i++)
{
int x = hd.x + dir[i][0], y = hd.y+ dir[i][1];
//排除边界和墙壁
if(x >= 0&&x < n&&y >= 0&&y < m&&map[x][y] != '#')
{
point t; //向第i个方向走一步后的位置
t.x = x;
t.y = y;
t.step = hd.step + 1;
t.time = hd.time + 1;
if(map[x][y] == 'x') t.time++;
//如果花费的时间比之前走到(x,y)少,则把t入队列
if(t.time < mintime[x][y])
{
mintime[x][y] = t.time;
Q.push(t);
}
}
}
}
return mintime[ax][ay];
}
int main()
{
while(scanf("%d%d",&n,&m) != EOF)
{
int sx,sy;
point start;
memset(map,0,sizeof(map));
for(int i = 0;i < n;i++)
{
scanf("%s",map[i]);
for(int j = 0;j < m;j++)
{
mintime[i][j] = INF;
if(map[i][j] == 'a')
{
ax = i;
ay = j;
}
if(map[i][j] == 'r')
{
sx = i;
sy = j;
}
}
}
start.x = sx;
start.y = sy;
start.step = 0;
start.time = 0;
mintime[sx][sy] = 0;
int mint = bfs(start);
//返回到达ANGEL位置的最少时间,有可能为无限大INF
if(mint<INF) printf("%d\n",mint);
else printf("Poor ANGEL has to stay in the prison all his life.\n");
}
return 0;
}