代码改变世界

leetcode - Spiral Matrix

2013-10-27 12:04  张汉生  阅读(139)  评论(0编辑  收藏  举报

 

 1 class Solution {
 2 public:
 3     vector<int> spiralOrder(vector<vector<int> > &matrix) {
 4         // Note: The Solution object is instantiated only once and is reused by each test case.
 5         vector<int> rlt;
 6         int m =matrix.size();
 7         if (m<=0)
 8             return rlt;
 9         int n = matrix[0].size();
10         if (n<=0)
11             return rlt;
12         int flag[4] = {0, m-1, 0, n-1};
13         int direction = 0; //left 2 right;
14         int i = 0;
15         while (true){
16             int j = 2 - 2 * (direction%2); //j=0 or j=2
17             if (flag[j]>flag[j+1])
18                 break;
19             int start = flag[j]*(1-direction/2) + flag[j+1]*(direction/2); // start of iteration
20             int delta = 1 - direction/2 - direction/2;
21             for (i=start; i<=flag[j+1] && i>=flag[j]; i+=delta){
22                 int rowIndex = i*(direction%2)+ flag[0]*(((direction+3)%4)/3) + flag[1]*(((direction+1)%4)/3);
23                 int colIndex = i*(1-direction%2)+flag[3]*(((direction+2)%4)/3) + flag[2]*(direction/3);
24                 rlt.push_back(matrix[rowIndex][colIndex]);
25             }
26             int index = 2*(direction%2) + ((direction+1)%4)/2;
27             flag[index] = flag[index] - ((direction+1)%4)/2 + ((direction+3)%4)/2;
28             direction = (direction+1)%4;
29         }
30         return rlt;
31     }
32 };
 1 class Solution {
 2 public:
 3     vector<int> spiralOrder(vector<vector<int> > &matrix) {
 4         // Note: The Solution object is instantiated only once and is reused by each test case.
 5         vector<int> rlt;
 6         int m =matrix.size();
 7         if (m<=0)
 8             return rlt;
 9         int n = matrix[0].size();
10         if (n<=0)
11             return rlt;
12         int flag[4] = {0, m-1, 0, n-1};
13         int direction = 0; //left 2 right;
14         int i = 0;
15         while (true){
16             int j = 2 - 2 * (direction%2); //j=0 or j=2
17             if (flag[j]>flag[j+1])
18                 break;
19             int start = flag[j]*(1-direction/2) + flag[j+1]*(direction/2); // start of iteration
20             int delta = 1 - direction/2 - direction/2;
21             for (i=start; i<=flag[j+1] && i>=flag[j]; i+=delta){
22                 int rowIndex = i*(direction%2)+ flag[0]*(((direction+3)%4)/3) + flag[1]*(((direction+1)%4)/3);
23                 int colIndex = i*(1-direction%2)+flag[3]*(((direction+2)%4)/3) + flag[2]*(direction/3);
24                 rlt.push_back(matrix[rowIndex][colIndex]);
25             }
26             int index = 2*(direction%2) + ((direction+1)%4)/2;
27             flag[index] = flag[index] - ((direction+1)%4)/2 + ((direction+3)%4)/2;
28             direction = (direction+1)%4;
29         }
30         return rlt;
31     }
32 };