大妮可� 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);
    	}
    }
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 机器学习教材中的例题询问
  • ¥15 求.net core 几款免费的pdf编辑器
  • ¥20 SQL server表计算问题
  • ¥15 C# P/Invoke的效率问题
  • ¥20 thinkphp适配人大金仓问题
  • ¥20 Oracle替换.dbf文件后无法连接,如何解决?(相关搜索:数据库|死循环)
  • ¥15 数据库数据成问号了,前台查询正常,数据库查询是?号
  • ¥15 算法使用了tf-idf,用手肘图确定k值确定不了,第四轮廓系数又太小才有0.006088746097507285,如何解决?(相关搜索:数据处理)
  • ¥15 彩灯控制电路,会的加我QQ1482956179
  • ¥200 相机拍直接转存到电脑上 立拍立穿无线局域网传