// Source : https://oj.leetcode.com/problems/spiral-matrix/ // Author : Hao Chen // Date : 2014-06-30 /********************************************************************************** * * 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]. * * **********************************************************************************/ #include #include #include #include using namespace std; vector spiralOrder(vector > &matrix) { vector v; int row = matrix.size(); if (row<=0) return v; int col = matrix[0].size(); if (col<=0) return v; int r, c; for (r=0, c=0; r<(row+1)/2 && c<(col+1)/2; r++, c++){ //top for(int i=c; ir && i>=c; i--){ v.push_back(matrix[row-r-1][i]); } //left for(int i=row-r-2; col-c-1>c && i>r; i--){ v.push_back(matrix[i][c]); } } return v; } void printArray(vector v) { cout << "["; for(int j=0; j > &vv) { for(int i=0; i > createMatrix(int n, int m) { vector< vector > vv; int cnt = 1; for(int i=0; i v; for(int j=0; j2){ n = atoi(argv[1]); m = atoi(argv[2]); } vector< vector > matrix = createMatrix(n, m); printMatrix(matrix); vector v = spiralOrder(matrix); printArray(v); return 0; }