P1135 奇怪的电梯 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
#include<iostream> #include<queue> #include<cstring> using namespace std; const int N=210; int K[N],n,A,B,vis[N]; struct node{ int now,step; }; #define check(a) (a>=1&&a<=n) void BFS(){ node begin,next; begin.now=A; begin.step=0; vis[begin.now]=1; queue<node> q; q.push(begin); while(!q.empty()){ begin=q.front(); q.pop(); if(begin.now==B){ cout<<begin.step<<endl; return ; } int c; c=begin.now+K[begin.now]; if(check(c)&&!vis[c]){ vis[c]=1; next.now=c; next.step=begin.step+1; q.push(next); } c=begin.now-K[begin.now]; if(check(c)&&!vis[c]){ vis[c]=1; next.now=c; next.step=begin.step+1; q.push(next); } } cout<<"-1"<<endl; } signed main(){ ios::sync_with_stdio(false); cin.tie(0);cout.tie(0); cin>>n>>A>>B; for(int i=1;i<=n;i++) cin>>K[i]; memset(vis,0,sizeof(vis)); BFS(); return 0; }
P1443 马的遍历 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
#include<iostream> #include<queue> #include<cstring> using namespace std; const int INF=0x3f3f3f3f; const int N=410; int n,m,x,y,vis[N][N],s[N][N]; struct node{ int dx,dy,step; }; #define check(a,b) (a>=1&&a<=n&&b>=1&&b<=m) void BFS(){ node begin,next; begin.dx=x; begin.dy=y; begin.step=0; vis[begin.dx][begin.dy]=-INF; queue<node> q; q.push(begin); while(!q.empty()){ begin=q.front(); q.pop(); int nx,ny; nx=begin.dx-1; ny=begin.dy+2; if(check(nx,ny)&&!vis[nx][ny]){ next.dx=nx; next.dy=ny; next.step=begin.step+1; vis[nx][ny]=next.step; q.push(next); } nx=begin.dx-1; ny=begin.dy-2; if(check(nx,ny)&&!vis[nx][ny]){ next.dx=nx; next.dy=ny; next.step=begin.step+1; vis[nx][ny]=next.step; q.push(next); } nx=begin.dx-2; ny=begin.dy+1; if(check(nx,ny)&&!vis[nx][ny]){ next.dx=nx; next.dy=ny; next.step=begin.step+1; vis[nx][ny]=next.step; q.push(next); } nx=begin.dx-2; ny=begin.dy-1; if(check(nx,ny)&&!vis[nx][ny]){ next.dx=nx; next.dy=ny; next.step=begin.step+1; vis[nx][ny]=next.step; q.push(next); } nx=begin.dx+1; ny=begin.dy+2; if(check(nx,ny)&&!vis[nx][ny]){ next.dx=nx; next.dy=ny; next.step=begin.step+1; vis[nx][ny]=next.step; q.push(next); } nx=begin.dx+1; ny=begin.dy-2; if(check(nx,ny)&&!vis[nx][ny]){ next.dx=nx; next.dy=ny; next.step=begin.step+1; vis[nx][ny]=next.step; q.push(next); } nx=begin.dx+2; ny=begin.dy+1; if(check(nx,ny)&&!vis[nx][ny]){ next.dx=nx; next.dy=ny; next.step=begin.step+1; vis[nx][ny]=next.step; q.push(next); } nx=begin.dx+2; ny=begin.dy-1; if(check(nx,ny)&&!vis[nx][ny]){ next.dx=nx; next.dy=ny; next.step=begin.step+1; vis[nx][ny]=next.step; q.push(next); } } for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ if(vis[i][j]==0){ vis[i][j]=-1; } } } vis[x][y]=0; } signed main(){ ios::sync_with_stdio(false); cin.tie(0);cout.tie(0); cin>>n>>m>>x>>y; memset(vis,0,sizeof(vis)); BFS(); for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ cout<<vis[i][j]<<" "; } cout<<endl; } return 0; }
hdu账号早日回归
标签:nx,begin,vis,基础,next,BFS,ny,step From: https://www.cnblogs.com/accbulb/p/18014072