抓住那头牛(POJ3278)
农夫知道一头牛的位置,想要抓住它。农夫和牛都位于数轴上
,农夫起始位于点N(0<=N<=100000),牛位于点K(0<=K<=100000)
。农夫有两种移动方式:
1、从X移动到X-1或X+1,每次移动花费一分钟
2、从X移动到2*X,每次移动花费一分钟
假设牛没有意识到农夫的行动,站在原地不动。农夫最少要
花多少时间才能抓住牛?
Sample Input
5 17
Sample Output
4
#include <iostream>
#include <queue>
#include <cstring>//用memset
#include <stdlib.h>
using namespace std;
int n,k;
int visited[100005];//判重标记,visited[i] = true 表示i已经扩展过
struct step
{
int x;//位置
int steps;//到达x所需的步数
step(int xx,int s):x(xx),steps(s){ }
};
queue<step> q;//队列,即Open表
int main()
{
cin>>n>>k;
memset(visited,0,sizeof(visited));
q.push(step(n,0));
visited[n]=1;
while(!q.empty())
{
step s=q.front();
if (s.x==k)//找到目标
{
cout<<s.steps<<endl;
return 0;
}
else
{//走x+1,x-1,x*2,
if (s.x-1>=0&&!visited[s.x-1])
{
q.push(step(s.x-1,s.steps+1));//将s压进去
visited[s.x-1]=1;
}
if (s.x+1<=100000&&!visited[s.x+1])
{
q.push(step(s.x+1,s.steps+1));
visited[s.x+1]=1;
}
if (s.x*2<=100000&&!visited[s.x*2])
{
q.push(step(s.x*2,s.steps+1));
visited[s.x*2]=1;
}
q.pop();
}
}
system("pause");
return 0;
}
POJ3984 迷宫问题
Description
定义一个二维数组:
int maze[5][5] = {
0, 1, 0, 0, 0,
0, 1, 0, 1, 0,
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 1, 0,
};
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
Input
一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。
Output
左上角到右下角的最短路径,格式如样例所示。
Sample Input
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
Sample Output
(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)
#include <iostream>
#include <cstring>
#include <queue>
#include <stdlib.h>
using namespace std;
int ma[7][7];
struct pos
{
int r,c;
int father;//父亲点在队列中的下标,-1 表示本节点是起点
pos(int rr=0,int cc=0,int ff=0):r(rr),c(cc),father(ff) { }//重载pos
};
pos que[100];//队列
int head,tail;//队列头尾指针
pos dir[4]={pos(-1,0),pos(1,0),pos(0,-1),pos(0,1)};//移动方向
int main()
{
memset(ma,0xff,sizeof(ma));
for (int i=1;i<=5;i++)
{
for (int j=1;j<=5;j++)
cin>>ma[i][j];
}
head=0;
tail=1;
que[0]=pos(1,1,-1);
while(head!=tail)//队列不为空
{
pos ps=que[head];
if(ps.r==5&&ps.c==5)//目标节点出队列
{
vector<pos> vt;
while(true)
{
vt.push_back(pos(ps.r,ps.c,0));
if(ps.father==-1)//起点
break;
ps=que[ps.father];
};
for(int i=vt.size()-1;i>=0;i--)
cout<<"("<<vt[i].r-1<<", "<<vt[i].c-1<<")"<<endl;
system("pause");
return 0;
}
else
{//队头节点不是目标节点
int r=ps.r,c=ps.c;
for (int i=0;i<4;i++)
{
if (!ma[r+dir[i].r][c+dir[i].c])
{
que[tail++]=pos(r+dir[i].r,c+dir[i].c,head);
//新扩展出来的节点的父节点在队列里的下标是head
ma[r+dir[i].r][c+dir[i].c]=1;
}
}
head++;
}
}
system("pause");
return 0;
}
来自北大郭炜老师