记得有一个大题,说的是给定一个n*n的矩阵,要求从1开始填充矩阵,最后的矩阵是蛇形的。即如下:
n=3, 7 8 1
6 9 2
5 4 3
n=4, 10 11 12 1
9 16 13 2
8 15 14 3
7 6 5 4
给出代码:
#include <iostream>
#include <vector>
using namespace std;
void snake(int m, vector<vector<int> > &a)
{int k = m;int i = 0; int j = 0;int count = 0;int l = 0;while (k >= 0){j = m - 1 - l;for (i = l; i < m - l; i++){count++;a[i][j] = count;}i = m - 1 - l;for (j = m - 2 - l; j >= l; j--){count++;a[i][j] = count;}j = l;for (i = m - 2 - l; i >= l; i--){count++;a[i][j] = count;}i = l;for (j = l + 1; j < m - 1 - l; j++){count++;a[i][j] = count;}k = k - 2;l++;}}int main()
{int m;cin >> m;vector<vector<int> > b(m);for (int i = 0; i < m; i++){b[i].resize(m);}snake(m, b);for (int i = 0; i < m; i++){for (int j = 0; j < m; j++){cout << b[i][j] << "\t";}cout << endl;}return 0;
}
结果:
616 17 18 19 20 1
15 30 31 32 21 2
14 29 36 33 22 3
13 28 35 34 23 4
12 27 26 25 24 5
11 10 9 8 7 6
请按任意键继续. . .