标签:
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3
,
You should return the following matrix:
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
class Solution { public: vector<vector<int> > generateMatrix(int n) { vector<vector<int> > result(n, vector<int>(n,0)); leftPos = 0; rightPos = n-1; topPos = 0; bottomPos = n-1; currentNum = 1; goWider(result,true); return result; } void goWider(vector<vector<int> > &matrix, bool direct) { if(direct) { for(int i = leftPos; i<= rightPos; i++) { matrix[topPos][i] = currentNum++; } topPos++; if(topPos > bottomPos) return; goDeeper(matrix, true); } else { for(int i = rightPos; i>= leftPos; i--) { matrix[bottomPos][i] = currentNum++; } bottomPos--; if(topPos > bottomPos) return; goDeeper(matrix, false); } } void goDeeper(vector<vector<int> > &matrix, bool direct) { if(direct) { for(int i = topPos; i<= bottomPos; i++) { matrix[i][rightPos]=currentNum++; } rightPos--; if(leftPos > rightPos) return; goWider(matrix, false); } else { for(int i = bottomPos; i>= topPos; i--) { matrix[i][leftPos] = currentNum++; } leftPos++; if(leftPos > rightPos) return; goWider(matrix, true); } } private: int currentNum; int leftPos; int rightPos; int topPos; int bottomPos; };
标签:
原文地址:http://www.cnblogs.com/qionglouyuyu/p/4854647.html