首页 > 其他 > 详细

编程算法 - 旋转矩阵 代码(C)

时间:2014-09-17 12:13:02      阅读:371      评论:0      收藏:0      [点我收藏+]

旋转矩阵 代码(C)


本文地址: http://blog.csdn.net/caroline_wendy


输出旋转矩阵, 使矩阵是按对角线螺旋上升, 在输出规则确定以后, 就可以判断, 上升规律是, 行列相加为定值.

所以采用两次循环的方法, 并且上下矩阵, 分开输出.

如:

  1   2   6   7  15
  3   5   8  14  16
  4   9  13  17  22
 10  12  18  21  23
 11  19  20  24  25

代码:

/*
 * main.cpp
 *
 *  Created on: 2014.6.12
 *      Author: Spike
 */

/*eclipse cdt, gcc 4.8.1*/

#include <stdio.h>

void output(int n)
{
	if (n < 0) return;

	const int MAX = 100;
	int a[MAX][MAX];

	int min = 1;
	int max = n*n;

	//上半个矩阵
	for (int i=0; i<n; i++) {
		for (int j=0; j<i+1; j++)
			if (i % 2 == 0) {
				a[i-j][j] = min++;
				a[n-1-i+j][n-1-j] = max--;
			} else {
				a[j][i-j] = min++;
				a[n-1-j][n-1-i+j] = max--;
			}
	}

	for (int i=0; i<n; i++) {
		for (int j=0; j<n; j++)
			printf("%3d%c", a[i][j], j == n - 1 ? ‘\n‘ : ‘ ‘);
	}

}

int main()
{
	output(5);
	return 0;
}


输出:

  1   2   6   7  15
  3   5   8  14  16
  4   9  13  17  22
 10  12  18  21  23
 11  19  20  24  25



bubuko.com,布布扣

编程算法 - 旋转矩阵 代码(C)

原文:http://blog.csdn.net/caroline_wendy/article/details/39338935

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!