1.二維陣列宣告 int[][] ans=new int[n][n];
2. left <= right && top <= bottom 跳出迴圈條件
1 class Solution { 2 public int[][] generateMatrix(int n) { 3 int[][] ans=new int[n][n]; 4 int num=1; 5 int top=0,bottom=n-1,left=0,right=n-1; 6 while(left <= right && top <= bottom){ 7 for(int i=left;i<=right;i++){ 8 ans[top][i]=num++; 9 } 10 top++; 11 for(int i=top;i<=bottom;i++){ 12 ans[i][right]=num++; 13 } 14 right--; 15 if(left<=right){ 16 for(int i=right;i>=left;i--){ 17 ans[bottom][i]=num++; 18 } 19 } 20 bottom--; 21 if(top<=bottom){ 22 for(int i=bottom;i>=top;i--){ 23 ans[i][left]=num++; 24 } 25 } 26 left++; 27 } 28 return ans; 29 } 30 }