|
@@ -0,0 +1,40 @@
|
|
|
+// 生成数组, 从大到小顺时针螺旋
|
|
|
+function generateSpiralArray(rows, cols) {
|
|
|
+ let arr = Array.from({ length: rows }, () => Array.from({ length: cols }));
|
|
|
+ let value = 1;
|
|
|
+ let top = 0, bottom = rows - 1, left = 0, right = cols - 1;
|
|
|
+
|
|
|
+ while (top <= bottom && left <= right) {
|
|
|
+ // 左 => 右
|
|
|
+ for (let i = left; i <= right; i++) {
|
|
|
+ arr[top][i] = value++;
|
|
|
+ }
|
|
|
+ top++;
|
|
|
+ // 上 => 下
|
|
|
+ for (let i = top; i <= bottom; i++) {
|
|
|
+ arr[i][right] = value++;
|
|
|
+ }
|
|
|
+ right--;
|
|
|
+
|
|
|
+ // 右 => 左
|
|
|
+ if (top <= bottom) {
|
|
|
+ for (let i = right; i >= left; i--) {
|
|
|
+ arr[bottom][i] = value++;
|
|
|
+ }
|
|
|
+ bottom--;
|
|
|
+ }
|
|
|
+
|
|
|
+ // 下 => 上
|
|
|
+ if (left <= right) {
|
|
|
+ for (let i = bottom; i >= top; i--) {
|
|
|
+ arr[i][left] = value++;
|
|
|
+ }
|
|
|
+ left++;
|
|
|
+ }
|
|
|
+
|
|
|
+ }
|
|
|
+
|
|
|
+ return arr;
|
|
|
+}
|
|
|
+
|
|
|
+const result2 = generateSpiralArray(6, 6);
|