首页 > 其他 > 详细

[LeetCode] Spiral Matrix

时间:2015-03-29 16:30:59      阅读:279      评论:0      收藏:0      [点我收藏+]

Spiral Matrix

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

For example,
Given the following matrix:

[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]

You should return [1,2,3,6,9,8,7,4,5].

解题思路:

分析题,没有什么难度,注意防止重复读取。读了“7”字形之后要判断。下面是代码:

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int> > &matrix) {
        vector<int> result;
        int rows = matrix.size();
        if(rows == 0){
            return result;
        }
        int cols = matrix[0].size();
        if(cols == 0){
            return result;
        }
        
        int rowsRead = 0;
        int colsRead = 0;
        
        while(rowsRead<(rows+1)/2 && colsRead<(cols + 1)/2){
            //输出上层边
            for(int i = colsRead; i < cols - colsRead; i++){
                result.push_back(matrix[rowsRead][i]);
            }
            //输出最右边
            for(int i = rowsRead + 1; i < rows - rowsRead; i++){
                result.push_back(matrix[i][cols - colsRead - 1]);
            }
            //若行数为奇数,并读到了中间一行,退出
            if((rowsRead + 1)*2 > rows){
                break;
            }
            //若列数为奇数,且读到了中间一列,跳出
            if((colsRead + 1)*2 > cols){
                break;
            }
            //输出最低边
            for(int i = cols - colsRead - 2; i>=colsRead; i--){
                result.push_back(matrix[rows - rowsRead - 1][i]);
            }
            //输出最左边
            for(int i = rows - rowsRead - 2; i>=rowsRead+1;i--){
                result.push_back(matrix[i][colsRead]);
            }
            rowsRead++;
            colsRead++;
        }
        
        return result;
    }
};

[LeetCode] Spiral Matrix

原文:http://blog.csdn.net/kangrydotnet/article/details/44727955

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!