Description | ||||||||||||
矩阵题目描述编写一个程序,将1~n2按行依次填入n×n的矩阵,执行若干条行或者列的循环移动的指令,再将数字按行依次取出。 指令如下:
输入第一行是一个整数K,表示样例的个数。 每个样例的第一行是两个整数n(1≤n≤10)和m(1≤m≤1000),分别表示矩阵的大小和指令的条数。 输出每行输出一个样例的结果,数字之间用一个空格隔开,行末无空格。 样例输入4 3 1 L 1 1 3 1 R 1 1 3 1 U 1 1 3 1 D 1 1 样例输出2 3 1 4 5 6 7 8 9 3 1 2 4 5 6 7 8 9 4 2 3 7 5 6 1 8 9 7 2 3 1 5 6 4 8 9 |
题意很简单,照着写即可,注意每次移动的替换,需要一个中间量储存值
#include<stdio.h>
int main(void)
{
int k;
scanf("%d", &k);
while(k--){
int n;
scanf("%d", &n);
int a[11][11] = {0};
int x=1;
for(int i=1;i<=n;i++){//建立矩阵
for(int j=1;j<=n;j++){
a[i][j]=x;
x++;
}
}
int m;
scanf("%d", &m);
while(m--){
char op;//读入指令
int x,y;
getchar();//读入换行符,防止op读入‘\n’;
scanf("%c %d %d", &op,&x, &y);
if(op == 'L'){
while(y--){//每次一格,循环y次
int temp = a[x][1];//分析每次移动的值
for(int j=1;j<=n-1;j++){
a[x][j] = a[x][j+1];
}
a[x][n] = temp;
}
}else if(op == 'R'){
while(y--){
int temp = a[x][n];
for(int j=n;j>=2;j--){
a[x][j] = a[x][j-1];
}
a[x][1] = temp;
}
}else if(op == 'U'){
while(y--){
int temp = a[1][x];
for(int j=1;j<=n-1;j++){
a[j][x] = a[j+1][x];
}
a[n][x] = temp;
}
}else if(op == 'D'){
while(y--){
int temp = a[n][x];
for(int j=n;j>=2;j--){
a[j][x] = a[j-1][x];
}
a[1][x] = temp;
}
}
}
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
printf("%d", a[i][j]);
if(!(n==i&&n==j)){
printf(" ");
}
}
}
printf("\n");
}
return 0;
}