spiral-matrix-ii 生成顺时针序列
Posted zl1991
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spiral-matrix-ii 生成顺时针序列相关的知识,希望对你有一定的参考价值。
Given an integer n, generate a square matrix filled with elements from 1 to n 2 in spiral order.
For example,
Given n =3,
You should return the following matrix:
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
注意左->右可遍历全,剩余两个方向遍历时需+1,最后一个方向掐头去尾避免重复遍历
class Solution { public: vector<vector<int> > generateMatrix(int n) { vector<vector<int>> result(n,vector<int>(n)); if(n==0) return result; int step = 1; int left = 0; int right = n-1; int top = 0; int bottom = n-1; while(left<=right && top<=bottom) { // 左->右 for(int i=left;i<=right;i++) { result[top][i] = step; step++; } //上->下 for(int i=top+1;i<=bottom;i++) { result[i][right] = step; step++; } //右->左 for(int i=right-1;i>=left;i--) { result[bottom][i] = step; step++; } //下->上 for(int i=bottom-1;i>top;i--) { result[i][left] = step; step++; } left++; right--; top++; bottom--; } return result; } };
以上是关于spiral-matrix-ii 生成顺时针序列的主要内容,如果未能解决你的问题,请参考以下文章
由围绕矩形形状顺时针方向移动的数字组成的图案(长度和宽度每次减小)[关闭]
Python数据结构:BF算法匹配括号回文链表生成螺旋矩阵移除列表元素计算后缀表达式的值顺时针旋转n维矩阵90度折半查找