包子小道消息@12/28/2019
有人的地方就有江湖,2019年北美tech industry的掌门人也是几家欢喜几家愁,有人上位自然就有人离开,铁打的硬盘流水的兵。However, 这些帮主们早已经家财万贯,只是为了自己在wiki上面的履历再添一笔罢了,我等吃瓜群众看看热闹,默默YY一下如果有一天是我,喂,醒醒啦(#`O′)!
Out
Promotions
YY了这么多消息,然而并没有卵用,赶紧埋头刷题吧少年们??。大家都在过假期,你在刷题,你不成功谁成功!你不牛逼谁牛逼!
我们遇到什么困难,也不要怕!微笑着面对它,消除恐惧的最好办法就是面对恐惧。坚持,才是胜利。加油,奥利给!
Baozi Training Leetcode 59 solution: Spiral Matrix II
Blogger: https://blog.baozitraining.org/2019/12/leetcode-solution-59-sprial-matrix-ii.html
Youtube: https://youtu.be/5NpvVznQlFA
博客园: https://www.cnblogs.com/baozitraining/p/12016806.html
B站: https://www.bilibili.com/video/av78743578/
Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
Example:
Input: 3
Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
Problem link
You can find the detailed video tutorial here
Straight forward question, could use Spiral Matrix exact same recursion algorithm to solve this, you can also watch that video tutorial here
Still needs pay attribute to this guy, had another great solution:
https://leetcode.com/problems/spiral-matrix-ii/discuss/22282/4-9-lines-Python-solutions
1 public int[][] generateMatrix(int n) {
2 assert n >= 0;
3
4 int[][] res = new int[n][n];
5
6 this.generateMatrixHelper(0, 0, n, n, res, 1);
7 return res;
8 }
9
10 private void generateMatrixHelper(
11 int i,
12 int j,
13 int rowSize,
14 int colSize,
15 int[][] matrix,
16 int num
17 ) {
18 if (rowSize <= 0 || colSize <= 0) {
19 return;
20 }
21
22 if (rowSize == 1 && colSize == 1) {
23 matrix[i][j] = num;
24 return;
25 }
26 if (rowSize == 1) {
27 for (int k = j; k < j + colSize; k++) {
28 matrix[i][k] = num;
29 num++;
30 }
31 return;
32 }
33
34 if (colSize == 1) {
35 for (int k = i; k < i + rowSize; k++) {
36 matrix[k][j] = num;
37 num++;
38 }
39 return;
40 }
41
42 // do the spiral
43 for (int k = j; k < j + colSize; k++) {
44 matrix[i][k] = num++;
45 }
46
47 for (int k = i + 1; k < i + rowSize; k++) {
48 matrix[k][j + colSize - 1] = num++;
49 }
50
51 for (int k = j + colSize - 2; k >= i; k--) {
52 matrix[i + rowSize - 1][k] = num++;
53 }
54
55 for (int k = i + rowSize - 2; k > i; k--) { // both the start and end need to be i, j, and also care about length
56 matrix[k][j] = num++;
57 }
58
59 this.generateMatrixHelper(i + 1, j + 1, rowSize - 2, colSize - 2, matrix, num);
60 }
Time Complexity: O(M*N) where M, N is row and col of matrix
Space Complexity: O(M*N) since we used list to store the result, where M, N is row and col of matrix