#include#include using namespace std; int main() { int cal = 1;//记录第几圈 奇数就是顺指针 偶数就是逆时针 vector >V;//V是二维数组 int row, col; cin >> row >> col; for (int i = 0; i < row; i++) { vector v; for (int j = 0; j < col; j++) { int val; cin >> val; v.push_back(val); } V.push_back(v); } //输出整个矩阵 //for (int i = 0; i < row; i++) //{ // for (int j = 0; j < col; j++) // { // cout << V[i][j]<<" "; // } // cout << endl; // //} int top = 0, bottle = row - 1, left = 0, right = col - 1;//记录矩阵边界 遍历一行/一列 边界减小 //这个循环条件为什么要+1 自己模拟一下 如果不+1 一次遍历完之后 会有一行还没遍历上就退出循环了 while (top != bottle + 1 || right != left - 1) { //顺时针 if (cal % 2 != 0) { for (int i = left; i <= right; i++)//从左到右 { cout << V[top][i] << " "; } top++; if (top == bottle + 1 || right == left - 1) break; for (int i = top; i <= bottle; i++)//从上到下 { cout << V[i][right] << " "; } right--; if (top == bottle + 1 || right == left - 1) break; for (int i = right; i >= left; i--)//从右到左 { cout << V[bottle][i] << " "; } bottle--; if (top == bottle + 1 || right == left - 1) break; for (int i = bottle; i >= top; i--)//从下到上 { cout << V[i][left] << " "; } left++; cal++; } //逆时针 (偶数圈 如果还可以继续遍历的话) else { for (int i = top; i <= bottle; i++)//从上到下 { cout << V[i][left] << " "; } left++; if (top == bottle + 1 || right == left - 1) break; for (int i = left; i <= right; i++)//从左到右 { cout << V[bottle][i] << " "; } bottle--; if (top == bottle + 1 || right == left - 1) break; for (int i = bottle; i >= top; i--)//从下到上 { cout << V[i][right] << " "; } right--; if (top == bottle + 1 || right == left - 1) break; for (int i = right; i >= left; i--)//从右到左 { cout << V[top][i] << " "; } top++; cal++; } } return 0; }
代码写的巨冗余....但AC了就懒得再改进了(笑)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)