// 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;
}
算法题1:蛇形打印矩阵
最新推荐文章于 2023-05-05 22:35:34 发布