问题描述
问题是解析指令机械臂的一系列命令 关于如何操作平桌上的积木。最初,有 是表上的 n 个块(编号从 0 到 n − 1),其中块为 bi 对于所有 0 ≤ i
用于操作块的机械臂的有效命令是:
-
将 a 移到 b 上
其中 a 和 b 是块编号,将块 a 放在块 b 上
onto:返回任何堆叠在块 a 和 b 顶部的块 到他们的初始位置。
-
将 a 移到 b 上
将块 a 放到包含块 b 的栈顶
over:将堆叠在块 a 顶部的任何块返回到它们的 初始位置。
-
把a堆在b上
移动由 a 块组成的一堆块,以及任何 被堆叠在块 a 上方,到块 b 上。块 b 顶部的所有块 在桩发生之前移动到它们的初始位置。 堆叠在 a 块上方的块在移动时保持其顺序。
-
把a堆在b上
放置由块 a 组成的一堆块,以及 堆叠在块 a 上方,到包含块 b 的堆栈的顶部。 堆叠在块 a 上方的块在以下情况下保持其原始顺序 移动了。
-
终止块世界中的操作。任何命令,其中 a = b 或者 a 和 b 在同一个块堆栈中是非法的 命令。所有非法命令都应该被忽略,并且应该没有 对块配置的影响。
输入:
输出:
此测试的输入:
8
move 1 onto 2
move 3 onto 4
pile 2 over 4
quit
我的代码:
#include<stdio.h>
#include<string.h>
int main(){
printf("please input n:");
int n;
scanf(" %d",&n);
int arr[n][n];
//this for storing their position
int i,j;
for(i=0;i<n;i++){
for(j=0;j<n;j++){
arr[i][j]=-1;
}
arr[i][0]=i;
}
//empty as -1
char str1[5],str2[5],cmd[20];//cmd is the complete line which will be spilt
int s,d;//source & destination
char st[5],dt[5];//char variable of int s and d
char* tk;//a pointer for strtok
int quit=0;
while(1){
s=-1;
d=-1;
while(!(s>=0 && s<n && d>=0 && d<n)){
fflush(stdin);
fgets(cmd,sizeof(cmd),stdin);
tk=strtok(cmd," ");
if(strcmp(tk,"quit\n")==0){
quit=1;
break;
}else{
strcpy(str1,tk);
tk=strtok(NULL," ");
strcpy(st,tk);
s=atoi(st);
tk=strtok(NULL," ");
strcpy(str2," ");
strcpy(dt,tk);
d=atoi(dt);
}
}
if(quit==1){
break;
}
//finally doing the commands
if(strcmp(str1,"move")==0){
if(strcmp(str2,"onto")==0){
//empty s but leave [0]
for(i=1;i<n && arr[s][i]!=-1;i++){
arr[arr[s][i]][0]=arr[s][i];
arr[s][i]=-1;
}
//empty d but leave [0]
for(i=1;i<n && arr[d][i]!=-1;i++){
arr[arr[d][i]][0]=arr[d][i];
arr[d][i]=-1;
}
//Now move s to d and empty [0]
i=1;
arr[d][i]=arr[s][0];
arr[s][0]=-1;
}else if(strcmp(str2,"over")==0){
//empty s but leave [0]
for(i=1;i<n && arr[s][i]!=-1;i++){
arr[arr[s][i]][0]=arr[s][i];
arr[s][i]=-1;
}
//move s to d and empty [0]
i=1;
while(arr[d][i]!=-1){
i++;
}
arr[d][i]=arr[s][0];
arr[s][0]=-1;
}
}else if(strcmp(str1,"pile")==0){
if(strcmp(str2,"onto")){
//empty d but leave [0]
for(i=1;i<n && arr[d][i]!=-1;i++){
arr[arr[d][i]][0]=arr[d][i];
arr[d][i]=-1;
}
//pile s to d
//empty of d
i=1;
//find end(empty) of s and store in j
j=0;
while(arr[s][j]!=-1){
j++;
}
//piling
int tj=0;//for iterating in s
j--;
while(j>=0){
arr[d][i]=arr[s][tj];
arr[s][tj]=-1;
j--;
tj++;
i++;
}
}else if(strcmp(str2,"over")){
//pile s to d
//find empty of d
i=0;
while(arr[d][i]!=-1){
i++;
}
//find end(empty) of s and store in j
j=0;
while(arr[s][j]!=-1){
j++;
}
//piling
int tj=0;//for iterating in s
j--;
while(j>=0){
arr[d][i]=arr[s][tj];
arr[s][tj]=-1;
j--;
tj++;
i++;
}
}
}
}
//print results
for(i=0;i<n;i++){
printf("%d:",i);
for(j=0;j<n && arr[i][j]!=-1;j++){
printf("%d ",arr[i][j]);
}
printf("\n");
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)