UVA 277 Puzzle
题意:输入5x5的字符串,输入操作,要求输出完成操作后的字符串。
注意:①输入的操作执行可能会越界,如果越界则按题目要求输出不能完成的语句。
②除了最后一次的输出外,其他输出均要在后面空一行。
③操作的最后一个换行符可能会占据str[0],需要用c来getchar()
1 #include "stdio.h" 2 #include "stdlib.h" 3 #include "string.h" 4 int noConfig=0,x,y,findEmpty=0,count=0,cmdcount=0; 5 //noConfig是指令不能执行(越界时),findEmpty是一边输入一边查找空字符的时候用,1为找到 6 //count是puzzle的计数,cmdcount是命令的计数 7 char str[5][5],cmd[100]; 8 //str是输入的字符串,cmd是操作指令 9 int judge(int exi,int exj)//判断越界 10 { 11 if(exi<0||exi>=5||exj<0||exj>=5) 12 { 13 return -1; 14 } 15 return 1; 16 } 17 18 int swap(int i,int j,char cmd)//str[exi][exj]交换str[i][j]中的空字符 19 { 20 int exi,exj; 21 // printf(" i=%d j=%d cmd=%c\n",i,j,cmd); 22 switch (cmd) 23 { 24 case 'A': 25 exi=i-1; 26 exj=j; 27 break; 28 case 'B': 29 exi=i+1; 30 exj=j; 31 break; 32 case 'L': 33 exi=i; 34 exj=j-1; 35 break; 36 case 'R': 37 exi=i; 38 exj=j+1; 39 break; 40 } 41 // printf("exi=%d exj=%d\n",exi,exj); 42 //判断 43 if(judge(exi,exj)==-1) 44 { 45 noConfig=1; 46 return -1; 47 } 48 //交换 49 str[y][x]=str[exi][exj]; 50 // printf(" Y,X:str[%d][%d]=%c\n",y,x,str[y][x]); 51 str[exi][exj]=' '; 52 // printf(" EXI,EXJ:str[%d][%d]=%c\n",y,x,str[exi][exj]); 53 y=exi; 54 x=exj; 55 // printf("after change:\n"); 56 // for(i=0;i<5;i++) 57 // { 58 // for(j=0;j<5;j++) 59 // { 60 // printf("%c",str[i][j]); 61 // } 62 // printf("\n"); 63 // } 64 return 1; 65 } 66 67 int main() 68 { 69 char c; 70 int i,j,k; 71 while(1) 72 { 73 noConfig=0; 74 cmdcount=0; 75 memset(str,'\0',sizeof(str)); 76 for(i=0;i<5;i++) 77 { 78 gets(str[i]); 79 if(str[0][0]=='Z') 80 { 81 return 0; 82 } 83 // for(j=0;j<5;j++)//边输入边查找 84 // { 85 // if(str[i][j]==' '||str[i][j]=='\0') 86 // { 87 // x=j; 88 // y=i; 89 // findEmpty=1; 90 //// printf("Y=%d X=%d\n",y,x); 91 // } 92 // } 93 } 94 for(i=0;i<5;i++) 95 { 96 for(j=0;j<5;j++) 97 { 98 if(str[i][j]==' '||str[i][j]=='\0') 99 { 100 x=j; 101 y=i; 102 // printf("Y=%d X=%d\n",y,x); 103 } 104 } 105 } 106 count++; 107 while((c=getchar())!='0') 108 { 109 cmd[cmdcount++]=c; 110 } 111 c=getchar();//用c取最后的换行符,不然str[0]会被换行符占据 112 for(i=0;i<cmdcount;i++) 113 { 114 if(swap(y,x,cmd[i])==-1) 115 break; 116 } 117 // fflush(stdin);写了这个就TIE 118 //输出结果 119 if(count!=1) 120 printf("\n");//注意这里,除最后一个输出外,其他的输完后都空一行 121 if(noConfig==1)//无结果 122 { 123 printf("Puzzle #%d:\n",count); 124 printf("This puzzle has no final configuration.\n"); 125 } 126 else 127 { 128 printf("Puzzle #%d:\n",count); 129 //输出 130 for(i=0;i<5;i++) 131 { 132 for(j=0;j<5;j++) 133 { 134 if(j!=0) 135 printf(" "); 136 printf("%c",str[i][j]); 137 } 138 printf("\n"); 139 } 140 } 141 } 142 return 0; 143 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步