大妮可� 2020-11-24 09:46 采纳率: 50%
浏览 4
已采纳

关于矩阵旋转,在不修改main()里面的代码的情况下,如何优化,可不可以再减少一些循环次数?

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>

int a[4][4];
void RotateLeft(int(&inout)[4][4])
{
	for (int y = 0; y <4; y++){
		for (int x = 0; x < 4; x++){
			a[y][x] = inout[x][4-1-y];
		}
	}
	for (int y = 0; y < 4; y++) {
		for (int x = 0; x < 4; x++) {
			inout[y][x] =a[y][x];
		}
	}
}

void Output(int(&a)[4][4])
{	
	for (int y = 0; y < 4; ++y){
		for (int x = 0; x < 4; ++x){	
			printf("%3d", a[y][x]);
		}
		puts("");
	}
}

int main()
{
	int a[4][4] =
	{
		{  0,  1,  2,  3},
		{  4,  5,  6,  7},
		{  8,  9, 10, 11},
		{ 12, 13, 14, 15},
	};
	Output(a);
	for (int i = 0; i < 4; i++){
		puts("== Rotate left ==");
		RotateLeft(a);
		Output(a);
	}
}
  • 写回答

1条回答 默认 最新

  • qq_25376897 2020-11-24 11:32
    关注
    #define _CRT_SECURE_NO_WARNINGS
    #include<stdio.h>
    #include<stdlib.h>
    
    void RotateLeft(int(&inout)[4][4])
    {
        int temp;
    	for (int y = 0; y < 4/2; y++){ //减少循环次数,一次循环里面同时处理多个坐标的变换
    		for (int x = y; x <4-1-y; x++){
    		    temp = inout[y][x];
    		    inout[y][x] = inout[x][4-1-y];
    		    inout[x][4-1-y] = inout[4-1-y][4-1-x];
    		    inout[4-1-y][4-1-x] = inout[4-1-x][y];
    		    inout[4-1-x][y] = temp;
    		}
    	}
    }
    
    void Output(int(&inout)[4][4])
    {	
    	for (int y = 0; y < 4; ++y){
    		for (int x = 0; x < 4; ++x){	
    			printf("%3d", inout[y][x]);
    		}
    		puts("");
    	}
    }
    
    int main()
    {
    	int a[4][4] =
    	{
    		{  0,  1,  2,  3},
    		{  4,  5,  6,  7},
    		{  8,  9, 10, 11},
    		{ 12, 13, 14, 15},
    	};
    	Output(a);
    	for (int i = 0; i < 4; i++){
    		puts("== Rotate left ==");
    		RotateLeft(a);
    		Output(a);
    	}
    }
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services