程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> leetcode - Spiral Matrix

leetcode - Spiral Matrix

編輯:C++入門知識

leetcode - 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:
    std::vector spiralOrder(std::vector > &matrix) {
		std::vector 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;
    }
};


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved