[Leetcode 98] 54 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 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]

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

Analysis:

The problem is a simulation problem. With the help of a direction variable, we can go through the matrix. When a new position is not valid, then we must change the direction.

For a index (i, j) to be valid, the following creteria must be satisfied:

1. i >=0 && i < row

2. j>=0 && j < col

3. m[i][j] is not visited

Direction changes from right -> down -> left -> up.

Code:

 1 class Solution {
 2 public:
 3     int row, col, MIN = (1<<31);
 4 
 5     vector<int> spiralOrder(vector<vector<int> > &matrix) {
 6         // Start typing your C/C++ solution below
 7         // DO NOT write int main() function
 8         vector<int> res;
 9         
10         if (matrix.size() == 0)
11             return res;
12             
13         row = matrix.size(), col = matrix[0].size();
14         int dir = 0, size = row * col;
15         int row_dir[4] = {0, 1, 0, -1};
16         int col_dir[4] = {1, 0, -1, 0};
17         
18         int i=0, j=-1, total = 0;
19         while (true) {
20             i += row_dir[dir];
21             j += col_dir[dir];
22             
23             if (isValid(i, j, matrix)) {
24                 res.push_back(matrix[i][j]);
25                 matrix[i][j] = MIN;
26                 total += 1;
27                 if (total == size) break;
28             } else {
29                 // reset to last valid position
30                 i -= row_dir[dir];
31                 j -= col_dir[dir];
32                 dir = (dir + 1) % 4;
33             }
34         }
35         
36         return res;
37     }
38     
39     bool isValid(int i, int j, vector<vector<int> > & m) {
40         return (i < row && i>=0) &&( j>=0 && j < col) && (m[i][j] != MIN);
41     }
42 };
View Code
原文地址:https://www.cnblogs.com/freeneng/p/3240599.html