码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Spiral Matrix

时间:2015-03-29 16:31:20      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:leetcode   c++   

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

标签:leetcode   c++   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!