[Leetcode] #54 Spiral Matrix

来源:互联网 发布:唐山技术支持盘古网络 编辑:程序博客网 时间:2024/05/09 21:14

Discription:

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

Solution:

vector<int> spiralOrder(vector<vector<int>>& matrix) {vector<int> result;if (matrix.empty()) return result;int m = matrix.size() - 1, n = matrix[0].size() - 1;for (int i = 0, j = 0; i <= m && j <= n; i++, j++){for (int k = j; k <= n; k++){result.push_back(matrix[i][k]);}for (int k = i + 1; k <= m; k++){result.push_back(matrix[k][n]);}for (int k = n - 1; k >= j && i != m; k--){result.push_back(matrix[m][k]);}for (int k = m - 1; k > i && j!=n; k--){result.push_back(matrix[k][j]);}m--;n--;}return result;}
参考:http://blog.csdn.net/fly_yr/article/details/48229999

0 0