HDU 1548
#include<bits/stdc++.h>
using namespace std;
int a[202];
int v[202];
int step[202];
int head,en;
int n,be,b;
int bfs()
{
queue<int>q;
q.push(be);
v[be]=1;
step[be]=0;
while(!q.empty())
{
head=q.front();
q.pop();
for(int i=0; i<2; i++)
{
if(i==0)
en=head+a[head];
else
en=head-a[head];
if(en<1||en>n)
continue;
if(!v[en])
{
q.push(en);
v[en]=1;
step[en]=step[head]+1;
}
if(en==b)
return step[en];
}
}
return -1;
}
int main()
{
while(cin>>n&&n!=0)
{
memset(v,0,sizeof(v));
memset(step,0,sizeof(step));
scanf("%d %d",&be,&b);
for(int i=1; i<=n; i++)
{
scanf("%d",&a[i]);
}
printf("%d\n",bfs());
}
}
HDU 1072
#include<bits/stdc++.h>
using namespace std;
int n,m;
int a[20][20];
int sum;
int b[4][2]={{-1,0},{1,0},{0,1},{0,-1}};
struct node{
int x,y;
int step,ti;
};
node tmp;
void bfs()
{
node t;
queue<node>q;
q.push(tmp);
while(!q.empty()){
tmp=q.front();
q.pop();
for(int i=0;i<4;i++){
t.x=tmp.x+b[i][0];
t.y=tmp.y+b[i][1];
t.step=tmp.step-1;
t.ti=tmp.ti+1;
if(t.x<=0||t.x>n||t.y<=0||t.y>m||t.step<=0)continue;
if(a[t.x][t.y]==0)continue;
if(a[t.x][t.y]==3)
{
sum=t.ti;
return ;
}
else if(a[t.x][t.y]==1){
q.push(t);
}
else if(a[t.x][t.y]==4)
{
t.step=6;
a[t.x][t.y]=1;
q.push(t);
}
}
}
}
int main()
{
int N;
int bn,bm,en,em;
cin>>N;
for(int i=0;i<N;i++){
scanf("%d %d",&n,&m);
for(int x=1;x<=n;x++){
for(int y=1;y<=m;y++){
scanf("%d",&a[x][y]);
if(a[x][y]==2){
tmp.x=x;
tmp.y=y;
tmp.step=6;
tmp.ti=0;
}
}
}
sum=-1;
bfs();
printf("%d\n",sum);
}
return 0;
}