class Solution { public: vector<vector<int> > generateMatrix(int n) { vector<vector<int> > result(n, vector<int>(n, 0)); int i = 0, j = 0, total = n * n, count = 1; while(count <= total) { for(;j < n && result[i][j] == 0;j++) { result[i][j] = count; count++; } if(count > total) break; j--; i++; for(; i < n && result[i][j] == 0; i++) { result[i][j] = count; count++; } if(count > total) break; i--; j--; for(;j >=0 && result[i][j] == 0; j--) { result[i][j] = count; count++; } if(count > total) break; j++; i--; for(;i >= 0 & result[i][j] == 0; i--) { result[i][j] = count; count++; } if(count > total) break; i++; j++; } return result; } };
4/06/2014
Leetcode -- Spiral Matrix II
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment