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

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

using namespace std;

vector<vector<int> > SpiralMatrix(int m) 
{
    //initialize a n*n vector<vector<int> >
    vector<vector<int> >  r(m, vector<int>(m,0));
    int k = 0;
	int n = m-1; //max index in vector, which starts at 0

	//generate spiral matrix layer by layer
    for(int layer = 0; layer <= n/2; ++layer)
    {
        //top
        for (int j = layer; j <= n-layer; ++j)
            r[layer][j] = ++k;
        //right
        for (int i = layer+1; i <= n-layer; ++i)
			r[i][n-layer] = ++k;
        //bottom
        for (int j = n-layer-1; j >= layer; --j)
            r[n-layer][j] = ++k;
        //left
        for (int i = n-layer-1; i >= layer+1; --i)
            r[i][layer] = ++k;
    }

    return r;
}

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

int main(int argc, char** argv)
{
	vector<vector<int> > v;
    PrintVV(v=SpiralMatrix(1));
    PrintVV(v=SpiralMatrix(3));
    PrintVV(v=SpiralMatrix(4));
    PrintVV(v=SpiralMatrix(7));
	
/*
1,

1, 2, 3,
8, 9, 4,
7, 6, 5,

1, 2, 3, 4,
12, 13, 14, 5,
11, 16, 15, 6,
10, 9, 8, 7,

1, 2, 3, 4, 5, 6, 7,
24, 25, 26, 27, 28, 29, 8,
23, 40, 41, 42, 43, 30, 9,
22, 39, 48, 49, 44, 31, 10,
21, 38, 47, 46, 45, 32, 11,
20, 37, 36, 35, 34, 33, 12,
19, 18, 17, 16, 15, 14, 13,

*/
return 0; }
View Program Text


Test Status