circualArray

来源:互联网 发布:mysql大神博客 编辑:程序博客网 时间:2024/05/22 03:01

顺时针遍历二维矩阵(螺旋数组)

剑指offer题目,也挺有意思的。
[ 牛客 url ] ( https://www.nowcoder.com/practice/9b4c81a02cd34f76be2659fa0d54342a?tpId=13&tqId=11172&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking )

如对于
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
则依次打印出数字: 1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.

代码逻辑不难,可能写的时候有点绕

class Solution {public:    vector<int> printMatrix(vector<vector<int> > matrix) {    int top = 0;        int bottom = matrix.size()-1;        int left = 0;        int right =  matrix[0].size()-1;        vector<int> ans;        while (top <= bottom && left <= right){            // 从左往右打印            for (int i = left;i <= right;i++) ans.push_back(matrix[top][i]);            // 从上往下打印              for (int j = top+1; j <= bottom; j++) ans.push_back(matrix[j][right]);            // 从左往右打印            if (top != bottom) {                for (int i = right-1; i>= left; i--) ans.push_back(matrix[bottom][i]);            }            // 从下往上打印      // 注意这里的循环终止条件            if (left != right){                for (int i = bottom-1; i > top; i--) ans.push_back(matrix[i][left]);            }            top ++; bottom --;            left ++; right --;        }        return ans;    }};
原创粉丝点击