Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3
,
You should return the following matrix:
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
public class Solution { int res[][]; int val=1; public int[][] generateMatrix(int n) { //主要是通过画图,判断每个分支的范围,本题还适应非方阵 res=new int[n][n]; int minRow=0; int maxRow=n-1; int minCol=0; int maxCol=n-1; int val=1; while(minRow<=maxRow&&minCol<=maxCol){ generate(minRow,maxRow,minCol,maxCol); minRow++; maxRow--; minCol++; maxCol--; } return res; } public void generate(int minRow,int maxRow,int minCol,int maxCol){ for(int i=minCol;i<=maxCol;i++){ res[minRow][i]=val++; } for(int i=minRow+1;i<=maxRow;i++){ res[i][maxCol]=val++; } for(int i=maxCol-1;i>=minCol;i--){ res[maxRow][i]=val++; } for(int i=maxRow-1;i>minRow;i--){ res[i][minCol]=val++; } } }
时间: 2024-10-29 10:36:54