k<=10 用三维数组,第三维标记 对k的余数,这样能把每种状态标记到。
#include<stdio.h>
#include<string.h>
char a[120][120];
struct f{
int x,y,step;
}b[120*120*4];
int book[120][120][10];
int main(){
int t;
scanf("%d",&t);
while(t--){
int n,m,k;
int startx=0,starty=0,endx=0,endy=0;
scanf("%d%d%d",&n,&m,&k);
for(int i=1;i<=n;i++)
scanf("%s",a[i]+1);
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
{
if(a[i][j]=='Y'){startx=i,starty=j;}
if(a[i][j]=='G'){endx=i,endy=j;}
}
if((startx==0&&starty==0)||(endx==0&&endy==0)){printf("Please give me another chance!\n");continue;}
int head=0,tail=1,flag=0;
memset(book,0,sizeof(book));
b[head].x=startx,b[head].y=starty,b[head].step=0;
book[startx][starty][1]=1;
while(head<tail){
int yy=b[head].step+1;
int next[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
for(int i=0;i<4;i++)
{
int tx=b[head].x+next[i][0],ty=b[head].y+next[i][1];
if(tx<1||tx>n||ty<1||ty>m||book[tx][ty][yy%k]) continue;
if(a[tx][ty]!='#'||yy%k==0){
b[tail].x=tx,b[tail].y=ty,b[tail++].step=yy;
book[tx][ty][yy%k]=1;
if(tx==endx&&ty==endy) {flag=1;break;}
}
}
if(flag) break;
head++;
}
if(flag){printf("%d\n",b[tail-1].step);}
else printf("Please give me another chance!\n");
}
return 0;
}
开始,3维数组的第三维大小开的是2,0代表障碍物全部消失,1代表全部存在,但有数据过不了(标记的状态少了);
#include<stdio.h>
#include<string.h>
char a[120][120];
struct f{
int x,y,step;
}b[120*120*4];
int book[120][120][2];
int main(){
int t;
scanf("%d",&t);
while(t--){
int n,m,k;
int startx=0,starty=0,endx=0,endy=0;
scanf("%d%d%d",&n,&m,&k);
for(int i=1;i<=n;i++)
scanf("%s",a[i]+1);
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
{
if(a[i][j]=='Y'){startx=i,starty=j;}
if(a[i][j]=='G'){endx=i,endy=j;}
}
if(startx==0&&starty==0||endx==0&&endy==0){printf("Please give me another chance!\n");continue;}
int head=0,tail=1,flag=0;
memset(book,0,sizeof(book));
b[head].x=startx,b[head].y=starty,b[head].step=0;
book[startx][starty][1]=1;
while(head<tail){
int yy=b[head].step+1;
int next[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
for(int i=0;i<4;i++)
{
int tx=b[head].x+next[i][0],ty=b[head].y+next[i][1];
if(tx<1||tx>n||ty<1||ty>m) continue;
if(yy%k==0&&book[tx][ty][0]) continue;
if(yy%k!=0&&book[tx][ty][1]) continue;
if(a[tx][ty]!='#'||yy%k==0){
if(yy%k==0){book[tx][ty][0]=1;}
else {book[tx][ty][1]=1;}
b[tail].x=tx,b[tail].y=ty,b[tail++].step=yy;
if(tx==endx&&ty==endy) {flag=1;break;}
}
}
if(flag) break;
head++;
}
if(flag){printf("%d\n",b[tail-1].step);}
else printf("Please give me another chance!\n");
}
return 0;
}
1 2 4 4 Y.#G #.##