hdu 1548
#include<stdio.h>
#define N 300
#define inf 999999999
int map[N][N],path[N],dis[N],n;
void dijkstra(int v0,int vn) {
int visit[N];
int min,w,i,j;
for(i=1;i<=n;i++) {
visit[i]=0;
dis[i]=map[v0][i];
if(dis[i]<inf)//路径初始化
path[i]=v0;
else
path[i]=-1;
}
visit[v0]=1;
for(i=1;i<=n;i++) {
min=inf;
for(j=1;j<=n;j++)
if(dis[j]<min&&visit[j]==0) {
min=dis[j];
w=j;
}
visit[w]=1;
for(j=1;j<=n;j++) {
if(visit[j]==0&&map[w][j]<inf) {
if(dis[w]+map[w][j]<dis[j])
dis[j]=dis[w]+map[w][j];
path[j]=w;//可记录路径
}
}
}
}
int main(){
int a,b,c,d,i,j;
while(scanf("%d",&n),n) {
scanf("%d%d",&a,&b);
for(i=1;i<=n;i++) {
dis[i]=inf;
for(j=1;j<=n;j++)
map[i][j]=i==j?0:inf;
}
for(i=1;i<=n;i++) {
scanf("%d",&c);
if(i+c<=n)
map[i][i+c]=1;
if(i-c>=1)
map[i][i-c]=1;
}
dijkstra(a,b);
if(dis[b]==inf)
printf("-1\n");
else
printf("%d\n",dis[b]);
}
return 0;
#define N 300
#define inf 999999999
int map[N][N],path[N],dis[N],n;
void dijkstra(int v0,int vn) {
int visit[N];
int min,w,i,j;
for(i=1;i<=n;i++) {
visit[i]=0;
dis[i]=map[v0][i];
if(dis[i]<inf)//路径初始化
path[i]=v0;
else
path[i]=-1;
}
visit[v0]=1;
for(i=1;i<=n;i++) {
min=inf;
for(j=1;j<=n;j++)
if(dis[j]<min&&visit[j]==0) {
min=dis[j];
w=j;
}
visit[w]=1;
for(j=1;j<=n;j++) {
if(visit[j]==0&&map[w][j]<inf) {
if(dis[w]+map[w][j]<dis[j])
dis[j]=dis[w]+map[w][j];
path[j]=w;//可记录路径
}
}
}
}
int main(){
int a,b,c,d,i,j;
while(scanf("%d",&n),n) {
scanf("%d%d",&a,&b);
for(i=1;i<=n;i++) {
dis[i]=inf;
for(j=1;j<=n;j++)
map[i][j]=i==j?0:inf;
}
for(i=1;i<=n;i++) {
scanf("%d",&c);
if(i+c<=n)
map[i][i+c]=1;
if(i-c>=1)
map[i][i-c]=1;
}
dijkstra(a,b);
if(dis[b]==inf)
printf("-1\n");
else
printf("%d\n",dis[b]);
}
return 0;
}
bfs
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
#define N 300
struct node {
int x,step;
}n1,n2,m;
int main() {
int A,B,a[N],i,n,visit[N],flag;
while(scanf("%d",&n),n) {
scanf("%d%d",&A,&B);
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
queue<node>q;
n1.x=A;
n1.step=0;
memset(visit,0,sizeof(visit));
visit[A]=1;
q.push(n1);
flag=0;
while(!q.empty()) {
m=q.front();
q.pop();
if(m.x==B) {
flag=1;
break;
}
n1.x=m.x+a[m.x];
n2.x=m.x-a[m.x];
if(n1.x>=1&&n1.x<=B&&visit[n1.x]==0) {
n1.step=m.step+1;
visit[n1.x]=1;
q.push(n1);
}
if(n2.x>=1&&n2.x<=B&&visit[n2.x]==0) {
n2.step=m.step+1;
visit[n2.x]=1;
q.push(n2);
}
}
if(flag==1)
printf("%d\n",m.step);
else
printf("-1\n");
}
return 0;
}