首页 > 代码库 > LeetCode Spiral Matrix II
LeetCode Spiral Matrix II
class Solution { public: vector<vector<int> > generateMatrix(int n) { vector<vector<int> > matrix; if (n < 1) return matrix; for (int i=0; i<n; i++) { matrix.push_back(vector<int>(n, 0)); } int left = 0, top = 0, right = n - 1, bottom = n - 1; int last = 1; while (left <= right && top <= bottom) { last = circle_walk(last, left, top, right, bottom, matrix); left++, top++, bottom--, right--; } return matrix; } int circle_walk(int start, int left, int top, int right, int bottom, vector<vector<int> >& map) { int rows = 0; if (map.size() < 1 || map[0].size() < 1) return start; // top row for (int i=left; i<=right; i++) { map[top][i] = start++; } // right col for (int i=top+1; i<=bottom; i++) { map[i][right] = start++; } // bottom row for (int i=right-1; bottom != top && i>=left; i--) { map[bottom][i] = start++; } // left col for (int i=bottom-1; left != right && i>top; i--) { map[i][left] = start++; } return start; } };
再水一发
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。