.Algorithm Gossip (47) 多维矩阵转一维矩阵

前言

This Series aritcles are all based on the book 《经典算法大全》; 对于该书的所有案例进行一个探究和拓展,并且用python和C++进行实现; 目的是熟悉常用算法过程中的技巧和逻辑拓展。

提出问题

47.Algorithm Gossip : 多维矩阵转一维矩阵

说明

有的时候,为了运算方便或资料储存的空间问题,使用一维阵列会比二维或多维阵列来得方便 ,例如上三角矩阵、下三角矩阵或对角矩阵,使用一维阵列会比使用二维阵列来得节省空间。

解法

深入理解进制转换的机制,这些就不算问题。

分析和解释

代码

#include <stdio.h>
#include <stdlib.h>
int main(void) {
	int arr1[3][4] = {{1, 2, 3, 4},
	{5, 6, 7, 8},
	{9, 10, 11, 12}};
	int arr2[12] = {0};
	int row, column, i;
	printf("原二维资料:
");
	for(row = 0; row < 3; row++) {
		for(column = 0; column < 4; column++) {
			printf("%4d", arr1[row][column]);
			}
		printf("
");
		}
	printf("
以列为主:");
	for(row = 0; row < 3; row++) {
		for(column = 0; column < 4; column++) {
			i = column + row * 4;
			arr2[i] = arr1[row][column];
			}
		}
	for(i = 0; i < 12; i++)
		printf("%d ", arr2[i]);
	printf("
以行为主:");
	for(row = 0; row < 3; row++) {
		for(column = 0; column < 4; column++) {
			i = row + column * 3;
			arr2[i] = arr1[row][column];
			}
		}
	for(i = 0; i < 12; i++)
		printf("%d ", arr2[i]);
	printf("
");
	return 0;
	}

拓展和关联

后记

参考书籍

  • 《经典算法大全》
  • 维基百科
原文地址:https://www.cnblogs.com/actanble/p/6711228.html