HDU-1728(逃离迷宫):
刚开始怎么做怎么WA。
后来看了下别人的写法,才知道 不能以一个点四个方向走,而是朝着一个点的方向走到头。
算一个深度。不像DFS那样,往下搜一个就算一个深度。大概意思就是这样。
#include<stdio.h> #include<string.h> const int maxn=100+10; struct node { int x,y; int t; }que[maxn*maxn]; node st,ed,t,tp; bool vis[maxn][maxn]; char str[maxn][maxn]; int n,m; int k; int xx[4]={0,0,-1,1},yy[4]={1,-1,0,0}; bool jud(int x,int y) { if(x<0||x>=n||y<0||y>=m) return false; if(str[x][y]=='*') return false; return true; } bool bfs() { int head=0,title=0; st.t=-1; vis[st.x][st.y]=1; que[title++]=st; while(head<title) { t=que[head++]; if(t.t>=k) continue; for(int i=0;i<4;i++) { tp.x=t.x+xx[i]; tp.y=t.y+yy[i]; tp.t=t.t+1; while(1) { if(jud(tp.x,tp.y)==0) break; if(tp.x==ed.x&&tp.y==ed.y){ // printf("tp.x==%d tp.y==%d\n",tp.x,tp.y); return true;} if(!vis[tp.x][tp.y]) { que[title++]=tp; vis[tp.x][tp.y]=1; } tp.x+=xx[i]; tp.y+=yy[i]; } } } } int main() { int tt; scanf("%d",&tt); while(tt--) { scanf("%d%d",&n,&m); for(int i=0;i<n;i++) scanf("%s",str[i]); scanf("%d%d%d%d%d",&k,&st.y,&st.x,&ed.y,&ed.x); st.x--; st.y--; ed.x--; ed.y--; memset(vis,0,sizeof(vis)); if(bfs()) printf("yes\n"); else printf("no\n"); } return 0; }
感觉应该先做这道题目的,感觉被坑了。
两题的思路一样,只不过练练的转弯数,被限定不能大于2.
#include<stdio.h> #include<string.h> const int maxn=1000+10; struct node { int x,y; int t; }que[maxn*maxn]; node st,ed,t,tp; int n,m,k; int str[maxn][maxn],vis[maxn][maxn]; int xx[4]={-1,0,1,0},yy[4]={0,1,0,-1}; bool panduan(int x,int y) { if(x<0||x>=n||y<0||y>=m) return false; if(str[x][y]!=0) return false; return true; } bool bfs() { int head=0,title=0; st.t=-1; que[title++]=st; vis[st.x][st.y]=1; while(head<title) { t=que[head++]; if(t.t>=k) continue; // printf("t.x==%d t.y%d\n",t.x,t.y); for(int i=0;i<4;i++) { tp.x=t.x+xx[i]; tp.y=t.y+yy[i]; tp.t=t.t+1; while(1) { if(tp.x==ed.x&&tp.y==ed.y){ return true;} if(panduan(tp.x,tp.y)==0) break; // printf("i=%d %d %d\n",i,tp.x,tp.y); if(!vis[tp.x][tp.y]) { que[title++]=tp; vis[tp.x][tp.y]=1; } tp.x+=xx[i]; tp.y+=yy[i]; } } } return false; } int main() { k=2; while(scanf("%d%d",&n,&m)!=EOF) { if(n==0&&m==0) break; for(int i=0;i<n;i++) for(int j=0;j<m;j++) scanf("%d",&str[i][j]); int tt; scanf("%d",&tt); while(tt--) { scanf("%d%d%d%d",&st.x,&st.y,&ed.x,&ed.y); st.x--,st.y--,ed.x--,ed.y--; if(str[st.x][st.y]!=str[ed.x][ed.y]||str[st.x][st.y]==0||str[ed.x][ed.y]==0){ puts("NO"); continue;} if(st.x==ed.x&&st.x==ed.y) { puts("NO"); continue; } memset(vis,0,sizeof(vis)); if(bfs()) puts("YES"); else puts("NO"); } } return 0; }