?LeetCode刷題實(shí)戰(zhàn)59:螺旋矩陣 II
算法的重要性,我就不多說(shuō)了吧,想去大廠,就必須要經(jīng)過(guò)基礎(chǔ)知識(shí)和業(yè)務(wù)邏輯面試+算法面試。所以,為了提高大家的算法能力,這個(gè)公眾號(hào)后續(xù)每天帶大家做一道算法題,題目就從LeetCode上面選 !
今天和大家聊的問(wèn)題叫做?螺旋矩陣 II,我們先來(lái)看題面:
https://leetcode-cn.com/problems/spiral-matrix-ii/
Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
題意
樣例
輸入: 3
輸出:
[
?[ 1, 2, 3 ],
?[?8, 9, 4 ],
?[?7, 6, 5 ]
]
解題

class?Solution?{
????public?int[][] generateMatrix(int?n) {
????????int?l = 0, r = n - 1, t = 0, b = n - 1;
????????int[][] mat = new?int[n][n];
????????int?num = 1, tar = n * n;
????????while(num <= tar){
????????????for(int?i = l; i <= r; i++) mat[t][i] = num++; // left to right.
????????????t++;
????????????for(int?i = t; i <= b; i++) mat[i][r] = num++; // top to bottom.
????????????r--;
????????????for(int?i = r; i >= l; i--) mat[b][i] = num++; // right to left.
????????????b--;
????????????for(int?i = b; i >= t; i--) mat[i][l] = num++; // bottom to top.
????????????l++;
????????}
????????return?mat;
????}
}
上期推文:
