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 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
| class Solution { public:
struct Runner { int leftBorder; int rightBorder; int topBorder; int downBorder; int dir; int counter; int x; int y; Runner(int n) { leftBorder = 0; rightBorder = n; topBorder = 0; downBorder = n; dir = 1; counter = 0; x = 0; y = 0; } };
void goRight(vector<vector<int>>& m, int n, Runner& r) { if (r.x < r.rightBorder) { ++r.counter; m[r.y][r.x] = r.counter; ++r.x; } else { r.dir = 2; ++r.topBorder; ++r.y; --r.x; } }
void goLeft(vector<vector<int>>& m, int n, Runner& r) { if (r.x >= r.leftBorder) { ++r.counter; m[r.y][r.x] = r.counter; --r.x; } else { r.dir = 3; --r.downBorder; --r.y; ++r.x; } }
void goDown(vector<vector<int>>& m, int n, Runner& r) { if (r.y < r.downBorder) { ++r.counter; m[r.y][r.x] = r.counter; ++r.y; } else { r.dir = 0; --r.rightBorder; --r.x; --r.y; } }
void goUp(vector<vector<int>>& m, int n, Runner& r) { if (r.y >= r.topBorder) { ++r.counter; m[r.y][r.x] = r.counter; --r.y; } else { r.dir = 1; ++r.leftBorder; ++r.x; ++r.y; } }
vector<vector<int>> generateMatrix(int n) { vector<vector<int>> result(n,vector<int>(n,0)); int num = n * n; Runner r(n); while(r.counter < num) { if (r.dir == 0) { goLeft(result,n,r); } else if (r.dir == 1) { goRight(result,n,r); } else if (r.dir == 2) { goDown(result,n,r); } else { goUp(result,n,r); } } return result; } };
|