Vintion's blog

~夜黑路滑,社会复杂~

Spiral Matrix

| Comments

Spiral Matrix

Problem

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
[1,2,3]
[4,5,6]
[7,8,9]

You should return[1,2,3,6,8,9,7,4,5]

Code
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
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int> > &matrix)
    {
        vector<int>result;
        result.clear();
        int row = matrix.size();
        if(row==0)return result;
        int col = matrix[0].size();
        int rowleft = 0, rowright = col -1;
        int coltop = 0, colbott = row -1;
        int i=0,j=0;
        int dir = 1;
        while(rowleft<=rowright&&coltop<=colbott)
        {
            switch(dir)
            {
                case 1:   //toright
                    while(rowleft<=rowright&&j>=rowleft&&j<=rowright)
                    {
                        result.push_back(matrix[i][j]);
                        j++;
                    }
                    j--;
                    i++;
                    coltop++;
                    dir = 2;
                    break;
                case 2: //tobott
                   while(coltop<=colbott&&i>=coltop&&i<=colbott)
                   {
                       result.push_back(matrix[i][j]);
                       i++;
                   }
                   i--;
                   j--;
                   rowright--;
                   dir = 3;
                   break;
                case 3: //toleft
                 while(rowleft<=rowright&&j>=rowleft&&j<=rowright)
                 {
                     result.push_back(matrix[i][j]);
                     j--;
                 }
                 j++;
                 i--;
                 colbott--;
                 dir = 4;
                 break;
                case 4:  //totop
                 while(coltop<=colbott&&i>=coltop&&i<=colbott)
                 {
                      result.push_back(matrix[i][j]);
                      i--;
                 }
                 i++;
                 j++;
                 rowleft++;
                 dir = 1;
                 break;
                 default:
                    break;
            }
        }
      
        return result;
    }
};

有很多种方法,这是自己的一种实

Comments