步骤:1.把输入的数字和空格保存。(这里用到gets函数读取整行)2.定位空格。3.输入指令。
#include<stdio.h> #include<string.h> char a[5][7];//声明数组 int main(){ memset(a,0,sizeof(a)); int blank_x=0; int blank_y=0; char s[100]; char c[10]; //输入网格 gets(a[0]); gets(a[1]); gets(a[2]); gets(a[3]); gets(a[4]); //定位空格 for(int x=0; x<5; x++) { for(int y=0; y<5; y++) { if(a[x][y] == ‘ ‘) { blank_x = x; blank_y = y; } } } gets(s);//输入指令 for(int i=0;s[i] != ‘0‘;i++){ if(s[i] == ‘A‘){ if(!a[blank_x-1][blank_y]) { printf("1 This puzzle has no final configuration.\n"); return 0;} a[blank_x][blank_y]=a[blank_x-1][blank_y]; a[blank_x-1][blank_y]=‘ ‘; blank_x=blank_x-1; } else if(s[i] == ‘B‘){ if(!a[blank_x+1][blank_y]) { printf("2 This puzzle has no final configuration.\n"); return 0;} a[blank_x][blank_y]=a[blank_x+1][blank_y]; a[blank_x+1][blank_y]=‘ ‘; blank_x=blank_x+1; } else if(s[i] == ‘L‘){ if(!a[blank_x][blank_y-1]) { printf("3 This puzzle has no final configuration.\n"); return 0;} a[blank_x][blank_y]=a[blank_x][blank_y-1]; a[blank_x][blank_y-1]=‘ ‘; blank_y=blank_y-1; } else if(s[i] == ‘R‘){ if(!a[blank_x][blank_y+1]) { printf("4 This puzzle has no final configuration.\n"); return 0;} a[blank_x][blank_y]=a[blank_x][blank_y+1]; a[blank_x][blank_y+1]=‘ ‘; blank_y=blank_y+1; } } //输出 puts(a[0]); puts(a[1]); puts(a[2]); puts(a[3]); puts(a[4]); return 0; }
OJ里还要加Puzzle #1:...
时间: 2024-10-13 07:28:11