API開發平臺,快速整合各種API介面
阿新 • • 發佈:2021-12-16
給你一個正整數n ,生成一個包含 1 到n2所有元素,且元素按順時針順序螺旋排列的n x n 正方形矩陣 matrix 。
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/spiral-matrix-ii
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
心之所向,素履以往 生如逆旅,一葦以航class Solution { public int[][] generateMatrix(int n) { int[][] ret = new int[n][n]; int idx = 1; int row1 = 0, col1 = 0; int row2 = n - 1, col2 = n - 1; while (row1 <= row2 && col1 <= col2) { if (row1 == row2) { for (int i = col1; i <= col2; ++i) { ret[row1][i] = idx++; } } else if (col1 == col2) { for (int i = row1; i <= row2; ++i) { ret[i][col1] = idx++; } } else { for (int i = col1; i < col2; ++i) { ret[row1][i] = idx++; } for (int i = row1; i < row2; ++i) { ret[i][col2] = idx++; } for (int i = col2; i > col1; --i) { ret[row2][i] = idx++; } for (int i = row2; i > row1; --i) { ret[i][col1] = idx++; } } row1++; col1++; row2--; col2--; } return ret; } }