码迷,mamicode.com
首页 > 编程语言 > 详细

算法题:蛇形打印矩阵

时间:2015-08-19 09:21:51      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:

  1 // Snake.cpp : print matric(n*n)。
  2 //////////// n=3:
  3 // 1 2 6
  4 // 3 5 7
  5 // 4 8 9
  6 //////////// n=4:
  7 // 1  2  6  7
  8 // 3  5  8  13
  9 // 4  9  12 14
 10 // 10 11 15 16
 11 
 12 #include "stdafx.h"
 13 #include "vector"
 14 #include "deque"
 15 #include "algorithm"
 16 #include "iostream"
 17 #include "iomanip"
 18 
 19 using namespace std;
 20 
 21 //辅助矩阵matric
 22 //           vector
 23 //             ||
 24 //             \/
 25 //1         <--deque
 26 //2 3       <--deque
 27 //6 5 4     <--deque
 28 //7 8       <--deque
 29 //9         <--deque
 30 vector<deque<int>> matric;
 31 
 32 
 33 //初始化辅助矩阵:
 34 //1
 35 //2 3
 36 //4 5 6
 37 //7 8
 38 //9
 39 void Init(int n)
 40 {
 41     matric.clear();
 42     int row = n * 2 - 1;
 43     int col = 0;
 44     int t = 1;
 45     for (int i = 1; i <= row; ++i) {
 46         if (i <= n) col = i;
 47         else col = row - i + 1;
 48         deque<int> vec;
 49         for (int j = 1; j <= col; ++j) {
 50             vec.push_back(t);
 51             t++;
 52         }
 53         matric.push_back(vec);
 54     }
 55 
 56 }
 57 
 58 //将辅助矩阵的奇数行逆序: 
59
//1 60 //2 3 61 //6 5 4 62 //7 8 63 //9 64 void Adjust(int n) 65 { 66 int row = n * 2 - 1; 67 for (int i = 1; i <= row; ++i) { 68 if (i % 2 == 1) { 69 reverse(matric.at(i-1).begin(), matric.at(i-1).end()); 70 } 71 } 72 } 73 74 void PrintInt(const int& n) 75 { 76 cout << setw(3) << n; 77 } 78 79 //打印辅助矩阵for testing 80 void PrintMatric(int n) 81 { 82 int row = n * 2 - 1; 83 int col = 0; 84 85 for (int i = 1; i <= row; ++i) { 86 for_each(matric.at(i - 1).begin(), matric.at(i - 1).end(), PrintInt); 87 cout << endl; 88 } 89 } 90 91 // 蛇形打印 92 // from matric: 93 //1 94 //2 3 1 2 6 95 //6 5 4 to 3 5 7 96 //7 8 4 8 9 97 //9 98 // 99 //n=4: 100 // 101 //1 102 //2 3 103 //6 5 4 1 2 6 7 15 104 //7 8 9 10 3 5 8 14 16 105 //15 14 13 12 11 to 4 9 13 17 22 106 //16 17 18 19 10 12 18 21 23 107 //22 21 20 11 19 20 24 25 108 //23 24 109 //25 110 // 打印前n个非空的deque的首元素,并pop_front 111 void PrintSnake(int n) 112 { 113 int row = n * 2 - 1; 114 for (int i = 1; i <= row; ++i) { 115 if (matric.at(i-1).size() == 0) 116 continue; 117 for (int j = 0; j < n; ++j) { 118 cout << setw(3) << matric.at(i-1+j).front(); 119 matric.at(i-1+j).pop_front(); 120 } 121 cout << endl; 122 } 123 } 124 125 int _tmain(int argc, _TCHAR* argv[]) 126 { 127 int n; 128 while (true) { 129 cin >> n; 130 if (n <= 0) break; 131 Init(n); 132 cout << "init:" << endl; 133 PrintMatric(n); 134 Adjust(n); 135 cout << "adjust:" << endl; 136 PrintMatric(n); 137 cout << "snake:" << endl; 138 PrintSnake(n); 139 } 140 141 return 0; 142 }

 

算法题:蛇形打印矩阵

标签:

原文地址:http://www.cnblogs.com/zhouguoguo/p/4741201.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!