publicint[][] generateMatrix(int n) {int k =1;// number to be put inint top =0;int left =0;int bottom = n -1;int right = n -1;int[][] res =newint[n][n];while (k <= n * n) {// fill top going rightfor (int i = left; i <= right; i++) { res[top][i] = k; k++; } top++;// fill right going downfor (int i = top; i <= bottom; i++) { res[i][right] = k; k++; } right--;// fill bottom going left, until "left"for (int i = right; i >= left; i--) { res[bottom][i] = k; k++; } bottom--;// fill left going up, until "top"for (int i = bottom; i >= top; i--) { res[i][left] = k; k++; } left++; }return res;}