给定矩阵行数和矩阵列数,顺时针打印矩阵(从0开始)
Posted 棋子
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了给定矩阵行数和矩阵列数,顺时针打印矩阵(从0开始)相关的知识,希望对你有一定的参考价值。
//石头 2016 / 3 / 28 21:38 : 32 #include<iostream> #include<vector> using namespace std; class Solution { public: void printMatrix(vector<vector<int> > &matrix) { int count = 0; if (matrix.empty()) return; int upEdge = 0; int leftEdge = 0; int rightEdge = matrix[0].size(); int downEdge = matrix.size(); bool end = false; char direction = ‘r‘; int i = 0; int j = 0; while (!end) { switch (direction) { case ‘r‘: if (j < rightEdge) { while (j < rightEdge) { matrix[i][j] = count++; j++; } upEdge += 1; direction = ‘d‘; i++; j--; } else end = true; break; case ‘d‘: if (i < downEdge) { while (i < downEdge) { matrix[i][j] = count++; i++; } direction = ‘l‘; j--; i--; rightEdge -= 1; } else end = true; break; case ‘l‘: if (j >= leftEdge) { while (j >= leftEdge) { matrix[i][j] = count++; j--; } direction = ‘u‘; i--; j++; downEdge -= 1; } else end = true; break; case ‘u‘: if (i >= upEdge) { while (i >= upEdge) { matrix[i][j] = count++; i--; } leftEdge += 1; direction = ‘r‘; j++; i++; } else end = true; break; default: break; } } } }; int main() { int m = 0; int n = 0; while (cin >> m >> n) { if (m != 0 && n != 0) { vector<vector<int> > maxtrix(m, vector<int>(n, 0)); class Solution test; vector<int> result; test.printMatrix(maxtrix); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { cout << maxtrix[i][j]; if (j != n - 1) cout << " "; } if (i != m - 1) cout << endl; } } } }
以上是关于给定矩阵行数和矩阵列数,顺时针打印矩阵(从0开始)的主要内容,如果未能解决你的问题,请参考以下文章