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

Spiral Matrix && Spiral Matrix II

时间:2015-06-10 17:30:10      阅读:106      评论: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].

解题思路:

求一个矩阵循环绕矩形输出元素。我们可以利用矩阵四条边的规则输出各个元素。左上---右上,右上---右下,右下---左下,左下---左上,按此顺序输出矩形的四条边,矩形由小到大,直到输出所有元素为止。代码如下:
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> res;
        if(matrix.size()==0) return res;
        int n=matrix.size();
	int m=matrix[0].size();
	
	for (int row=0;row<n/2+1;row++)
	{
		int i=row;
		int j=i;
		for (j=i;j<(m-row);j++)
		{
			res.push_back(matrix[i][j]);
			if (res.size()==(n*m))
			{
				return res;
			}
		}
		j--;
		for (i=row+1;i<(n-row);i++)
		{
			res.push_back(matrix[i][j]);
			if (res.size()==(n*m))
			{
				return res;
			}
		}
		i--;
		for (j=j-1;j>=row;j--)
		{
			res.push_back(matrix[i][j]);
			if (res.size()==(n*m))
			{
				return res;
			}
		}
		j++;
		for (i=i-1;i>=row+1;i--)
		{
			res.push_back(matrix[i][j]);
			if (res.size()==(n*m))
			{
				return res;
			}
		}
	}
	return res;
        
    }
};

Spiral Matrix  II

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

For example,
Given n = 3,

You should return the following matrix:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]
class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        int x=0;
	vector<vector<int>> res;
	vector<int> temp(n,0);
	for (int i=0;i<n;i++)
	{
		res.push_back(temp);
	}
	for (int row=0;row<n/2+1;row++)
	{
		int i=row;
		int j=i;
		for (j=i;j<(n-row);j++)//左---右
		{
			res[i][j]=++x;
		}
		j--;
		for (i=row+1;i<(n-row);i++)//上---下
		{
			res[i][j]=++x;
		}
		i--;
		for (j=j-1;j>=row;j--)//右---左
		{
			res[i][j]=++x;
		}
		j++;
		for (i=i-1;i>=row+1;i--)//下---上
		{
			res[i][j]=++x;
		}
	}
	return res;
        
    }
};




Spiral Matrix && Spiral Matrix II

标签:

原文地址:http://blog.csdn.net/sinat_24520925/article/details/46442417

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