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

leetcode - Spiral Matrix

时间:2014-10-23 00:11:12      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:style   color   io   os   ar   for   sp   on   amp   

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].

class Solution {
public:
    std::vector<int> spiralOrder(std::vector<std::vector<int> > &matrix) {
		std::vector<int> res;
		if(matrix.size() == 0) return res;
		int rowBgn = 0, rowEnd = matrix.size() - 1,colBgn = 0,colEnd = matrix[0].size() - 1;
		while (rowBgn <= rowEnd && colBgn <= colEnd)
		{
			//right
			for(int i = colBgn; i <= colEnd; i++)
			{
				res.push_back(matrix[rowBgn][i]);
			}
			rowBgn++;
			//Down
			for(int i = rowBgn; i <= rowEnd; i++)
			{
				res.push_back(matrix[i][colEnd]);
			}
			colEnd--;
			//left
			if (rowBgn <= rowEnd)
			{
				for(int i = colEnd; i >= colBgn; i--)
				{
					res.push_back(matrix[rowEnd][i]);
				}
			}
			rowEnd--;
			//up
			if (colBgn <= colEnd)
			{
				for(int i = rowEnd; i >= rowBgn; i--)
				{
					res.push_back(matrix[i][colBgn]);
				}
			}
			colBgn++;
		}
		return res;
    }
};


leetcode - Spiral Matrix

标签:style   color   io   os   ar   for   sp   on   amp   

原文地址:http://blog.csdn.net/akibatakuya/article/details/40383489

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