1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108

#include <iostream>
#include <iomanip>
#include <vector>

using namespace std;

vector<int>  SpiralOrder(vector<vector<int> > &matrix) 
{
	if (matrix.size() <= 0)return vector<int>();

    int row = matrix.size();
    int col = matrix[0].size(); 
    vector<int>  r;
    r.reserve(row*col);
	
	int top = 0;
	int bottom = row - 1;
	int left = 0;
	int right = col - 1;
	
	while (top < bottom && left < right)
	{
		for (int j = left; j <= right; ++j)
			r.push_back(matrix[top][j]);
		++top;
		
		for (int i = top; i <= bottom; ++i)
			r.push_back(matrix[i][right]);
		--right;
		
		for (int j = right; j >= left; --j)
			r.push_back(matrix[bottom][j]);
		--bottom;
		
		for (int i = bottom; i >= top; --i)
			r.push_back(matrix[i][left]);
		++left;
	}
	
	if (left < right && top == bottom) //for odd fat matrix
		for (int j = left; j <= right; ++j)
			r.push_back(matrix[top][j]);
	
	if (top < bottom && left == right)//for odd len matrix
		for (int i = top; i <= bottom; ++i)
			r.push_back(matrix[i][right]);
	
	if (top == bottom && left == right) //for odd sqaure matrix
		r.push_back(matrix[top][left]);
	
    return r;
}

void InitVV(vector<vector<int> >& v)
{
	int k = 0;
    for (int i = 0; i < v.size(); ++i)
    {
        for (int j = 0; j < v[i].size(); ++j)
        {
			v[i][j] = ++k;
            cout<< setw(4) << v[i][j] << ',';
        }
		
        cout << '\n';
    }
	
    cout << endl;
}

void PrintV(vector<int> v)
{
    cout << "Spiral order:";
	for (int i = 0; i < v.size(); ++i)
    {
            cout<< setw(4) << v[i] << ',';
    }
    
    cout << endl; cout << endl;
}

int main(int argc, char** argv)
{
	vector<int> v;
	
	//Empty matrices
    /*vector<vector<int> > m(0, vector<int>(0, 0));
InitVV(m);
PrintV(v=SpiralOrder(m));*/
//Square matrices (size_of_row == size_of_column) vector<vector<int> > m0(3, vector<int>(3, 0)); InitVV(m0); PrintV(v=SpiralOrder(m0)); //Fat matrices (size_of_row < size_of_column) vector<vector<int> > m1(3, vector<int>(5, 0)); InitVV(m1); PrintV(v=SpiralOrder(m1)); //Lean matrices (size_of_row > size_of_column) vector<vector<int> > m2(4, vector<int>(2, 0)); InitVV(m2); PrintV(v=SpiralOrder(m2)); return 0; }
View Program Text


Test Status