二维数组:螺旋矩阵II
题目表述:
示例 1:
输入: 3 输出: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ]
/* 螺旋矩阵II */ public class Solution { public static void main(String[] args) { Solution solution = new Solution(); int n = 5;//矩阵大小 int[][] res = solution.generateMatrix(n); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { System.out.print(res[i][j] + " "); } System.out.println(); } } private int[][] generateMatrix(int n) { int[][] res = new int[n][n]; int loop = 0;//判断边界 int count = 1;//输出值 int start = 0; //控制循环输出的起点如(0,0) (1,1) (2,2) int i, j;//二维数组游标 while (loop++ < n / 2) {//判断边界,从1开始 //上排从左到右 for (j = start; j < n - loop; j++) { res[start][j] = count++; } //右排从上到下 for (i = start; i < n - loop; i++) { res[i][j] = count++; } //下排从右到左 for(;j>=loop;j--){ res[i][j] = count++; } //左排从下到上 for(;i>=loop;i--){ res[i][j] = count++; }
//外层往里层渗透 start++; } //奇数时需要赋值最正中间坐标元素 if(n%2>0){ res[start][start] = count; } return res; } }
Tips:本题出自LeetCode 仅学习参考