1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
| class Solution { public: bool checkborder(vector<vector<int>> m, int x, int y) { bool isborder = false; int size = m.size(); if (x < 0 || y < 0 || x > size - 1 || y > size - 1 || m[x][y] != 0) isborder = true; return isborder; } vector<vector<int>> generateMatrix(int n) { int dx[] = { 0, 1, 0, -1 }; int dy[] = { 1, 0, -1, 0 }; int right = 0, down = 1, left = 2, up = 3; int direction = right; vector<vector<int>> matrix(n, vector<int>(n, 0)); int elem = 1; int x = 0, y = 0; int nextx, nexty; while (elem <= n * n) { matrix[x][y] = elem; nextx = x + dx[direction], nexty = y + dy[direction]; if (checkborder(matrix, nextx, nexty)) { direction++; if (direction > up) direction = right; nextx = x + dx[direction], nexty = y + dy[direction]; } x = nextx, y = nexty; elem++; } return matrix; } };
class Solution { public: vector<vector<int>> generateMatrix(int n) { vector<vector<int>> res(n, vector<int>(n, 0)); int startx = 0, starty = 0; int loop = n / 2; int mid = n / 2; int count = 1; int offset = 1; int i,j; while (loop --) { i = startx; j = starty;
for (j = starty; j < n - offset; j++) { res[startx][j] = count++; } for (i = startx; i < n - offset; i++) { res[i][j] = count++; } for (; j > starty; j--) { res[i][j] = count++; } for (; i > startx; i--) { res[i][j] = count++; }
startx++; starty++;
offset += 1; }
if (n % 2) { res[mid][mid] = count; } return res; } };
|