算法题1:蛇形打印矩阵

// Snake.cpp : print matric(n*n)。
 n=3:
// 1 2 6
// 3 5 7
// 4 8 9
 n=4:
// 1  2  6  7
// 3  5  8  13
// 4  9  12 14
// 10 11 15 16

#include "stdafx.h"
#include "vector"
#include "deque"
#include "algorithm"
#include "iostream"
#include "iomanip"

using namespace std;

//associate matric
//           vector
//             ||
//             \/
//1         <--deque
//2 3       <--deque
//6 5 4     <--deque
//7 8       <--deque
//9         <--deque
vector<deque<int>> matric;


//init associate matric:
//1
//2 3
//4 5 6
//7 8
//9
void Init(int n)
{
	matric.clear();
	int row = n * 2 - 1;
	int col = 0;
	int t = 1;
	for (int i = 1; i <= row; ++i) {
		if (i <= n) col = i;
		else col = row - i + 1;
		deque<int> vec;
		for (int j = 1; j <= col; ++j) {
			vec.push_back(t);
			t++;
		}
		matric.push_back(vec);
	}

}

//odd line reverse
//1
//2 3
//6 5 4
//7 8
//9
void Adjust(int n)
{
	int row = n * 2 - 1;
	for (int i = 1; i <= row; ++i) {
		if (i % 2 == 1) {
			reverse(matric.at(i-1).begin(), matric.at(i-1).end());
		}
	}
}

void PrintInt(const int& n)
{
	cout << setw(3) << n;
}

//print associate metric for testing
void PrintMatric(int n)
{
	int row = n * 2 - 1;
	int col = 0;

	for (int i = 1; i <= row; ++i) {
		for_each(matric.at(i - 1).begin(), matric.at(i - 1).end(), PrintInt);
		cout << endl;
	}
}

// PrintSnake
// from matric:
//1                          
//2 3               1 2 6
//6 5 4     to      3 5 7          
//7 8               4 8 9         
//9                          
//                            
//n=4:                             
//                            
//1                             
//2  3
//6  5  4               1  2  6  7
//7  8  9  10           3  5  8  13
//15 14 13 12 11   to   4  9  12 14
//16 17 18 19           10 11 15 16
//22 21 20
//23 24
//25
// print front element of first n deques(not empty), and pop_front
void PrintSnake(int n)
{
	int row = n * 2 - 1;
	for (int i = 1; i <= row; ++i) {
		if (matric.at(i-1).size() == 0)
			continue;
		for (int j = 0; j < n; ++j) {
			cout << setw(3) << matric.at(i-1+j).front();
			matric.at(i-1+j).pop_front();
		}
		cout << endl;
	}
}

int _tmain(int argc, _TCHAR* argv[])
{
	int n;
	while (true) {
		cin >> n;
		if (n <= 0) break;
		Init(n);
		cout << "init:" << endl;
		PrintMatric(n);
		Adjust(n);
		cout << "adjust:" << endl;
		PrintMatric(n);
		cout << "snake:" << endl;
		PrintSnake(n);
	}

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值