天天看點

54. Spiral Matrix

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

解析

  • 自己親自寫才知道很多細節問題:
  • bug1:

    y0==y1

    寫成

    y0=y1

    指派語句
  • bug2:

    for (int row = x1 - 1; row > x0;row--)

    小标越界

    row=x1+1

  • bug3: 輸入為空矩陣判斷

    if ( matrix.empty())

    後面判斷

    row<=0||col<=0

    此時已經出現問題了
class Solution_54 {
public:
	void help(vector<vector<int>>& matrix,vector<int> &res, int x0, int y0, int x1, int y1)
	{
		if (x0==x1&&y0==y1)
		{
			res.push_back(matrix[x0][y0]);
		}else if (x0==x1) //最後一行
		{
			for (int i = y0; i <= y1;i++)
			{
				res.push_back(matrix[x0][i]);
			}
		}else if (y1==y0)
		{
			for (int i = x0; i <= x1;i++)
			{
				res.push_back(matrix[i][y0]);
			}
		}
		else
		{
			for (int col = y0; col <= y1;col++) 
			{
				res.push_back(matrix[x0][col]);
			}
			for (int row = x0 + 1; row <= x1;row++)
			{
				res.push_back(matrix[row][y1]);
			}
			for (int col = y1 - 1; col >= y0;col--)
			{
				res.push_back(matrix[x1][col]);
			}
			for (int row = x1 - 1; row > x0;row--)
			{
				res.push_back(matrix[row][y0]);
			}
		}
		return;
	}

	vector<int> spiralOrder(vector<vector<int>>& matrix) {
		vector<int> res;
		if ( matrix.empty()) //
		{
			return vector<int>(); //res;
		}
		int row = matrix.size();
		int col = matrix[0].size(); //後面判斷錯誤:row <= 0 || col <= 0 ,需要計算row,col調用size()出錯,需要在函數開始判斷

		int x0 = 0, y0 = 0, x1 = row - 1, y1 = col - 1;
		while (x0<=x1&&y0<=y1)
		{
			help(matrix,res, x0, y0, x1, y1);
			x0++;
			y0++;
			x1--;
			y1--;
		}

		return res;
	}
};
           

題目來源

  • 矩陣的操作

C/C++基本文法學習

STL

C++ primer