您的位置:首页 > 其它

LeetCode Spiral Matrix

2013-12-11 07:45 211 查看
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]
.

这道题如果搞得像麻绳一样缠在一起就无法解开了。

如果一条一条分好了,就势如破竹,一下子解开了。

遇上这样的题还是先不要想优化的算法比较妥当,尤其是不要吝啬空间的使用,否则会乱成一堆,所以我这里用了四个下标,使得程序更加清晰点。

思路:

1 先剥开最外一层matrix,然后是下一层,一层一层搞定

注意:

1 直接使用多个下标,不要使用计算的方法,利用一个下标计算出其他三个下标,那样做很容易出错。

2 最后结束条件:剩下一行或者一列的时候,结束循环,额外写一点代码处理这最后一行或者一列。



class Solution {
public:
	vector<int> spiralOrder(vector<vector<int> > &matrix) 
	{
		vector<int> res;
		int row = matrix.size();
		if (row < 1) return res;
		int col = matrix[0].size();

		int rowUpper = 0, rowLower = row - 1;
		int colLeft = 0, colRight = col - 1;

		while (rowUpper < rowLower && colLeft < colRight)
		{
			//插入最顶行
			res.insert(res.end(), matrix[rowUpper].begin()+colLeft
				, matrix[rowUpper].begin()+colRight+1);
			rowUpper++;
			//插入最右列
			for (int i = rowUpper; i < rowLower; i++)
			{
				res.push_back(matrix[i][colRight]);
			}
			colRight--;
			//插入最下面一行
			res.insert(res.end(),matrix[rowLower].rbegin()+colLeft, 
				matrix[rowLower].rbegin()+colRight+2);
			rowLower--;
			//插入最左边一列
			for (int i = rowLower; i >= rowUpper; i--)
			{
				res.push_back(matrix[i][colLeft]);
			}
			colLeft++;
		}
		if (rowUpper == rowLower)
		{
			//插入最后一行,注意下标和循环中的有点不一样
 			res.insert(res.end(), matrix[rowUpper].begin()+colLeft
				, matrix[rowUpper].begin()+colRight+1);
		}
		else if (colLeft == colRight)
		{
			//插入最后一列,注意下标和循环中的有点不一样
 			for (int i = rowUpper; i <= rowLower; i++)
			{
				res.push_back(matrix[i][colRight]);
			}
		}
		return res;
	}
};


2014-1-29 更新

程序一样的思路,不过可以更加轻易的驾驭下标了

class Solution {
public:
	vector<int> spiralOrder(vector<vector<int> > &matrix) 
	{
		vector<int> rs;
		int row = matrix.size()-1;
		if (row < 0) return rs;
		int col = matrix[0].size()-1;

		int i = 0;
		for ( ; i < row && i < col; i++, row--, col--)
		{
			for (int j = i; j < col; j++)
			{
				rs.push_back(matrix[i][j]);
			}
			for (int j = i; j < row; j++)
			{
				rs.push_back(matrix[j][col]);
			}
			for (int j = col; j > i ; j--)
			{
				rs.push_back(matrix[row][j]);
			}
			for (int j = row; j > i ; j--)
			{
				rs.push_back(matrix[j][i]);
			}
		}
		if (i == row) rs.insert(rs.end(),
			matrix[row].begin()+i, matrix[row].begin()+col+1);
		else if (i == col)
		{
			for ( ; i <= row; i++)
			{
				rs.push_back(matrix[i][col]);
			}
		}
		return rs;
	}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: