一道面试题,直接上代码和运行结果:
<span style="font-size:14px;">/*
*Created on 2016年4月3日
*Copyright 2016 Yong Cai Limited crop. All Rights Reserved
*
*7289***0@qq.com
*/
package org.cy.com;
import java.util.Scanner;
public class SheXingJuZhen {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.println("n = " + n);
printMatrix(compute(n), n);
}
private static int[][] compute(int n){
int[][] res = new int[n][n];
int start = 0;
int end = n * n;
int rightStartRow = 0;
int downEndCol = n - 1;
int leftStartRow = n-1;
int upEndCol = 0;
while(end != start){
//System.out.println("start:" + start);
//向右,操作行
for(int i = upEndCol; i < n;i++){
if(res[rightStartRow][i] == 0){
start ++;
res[rightStartRow][i] = start;
}
}
rightStartRow ++;
//向下,操作列
for(int i = rightStartRow;i < n;i++){
if(res[i][downEndCol] == 0){
start ++;
res[i][downEndCol] = start;
}
}
downEndCol--;
//向左,操作行
for(int i = downEndCol;i >= 0;i--){
if(res[leftStartRow][i] == 0){
start ++;
res[leftStartRow][i] = start;
}
}
leftStartRow --;
//向上,操作列
for(int i = leftStartRow;i >= 0;i--){
if(res[i][upEndCol] == 0){
start ++;
res[i][upEndCol] = start;
}
}
upEndCol ++;
}
return res;
}
private static void printMatrix(int[][] res,int n){
int max = n * n;
int len = String.valueOf(max).length();
for(int i=0;i < n;i++){
for(int j=0;j < n;j++){
if(String.valueOf(res[i][j]).length() == len){
System.out.print(res[i][j] + " ");
}else{
int sub = len - String.valueOf(res[i][j]).length();
String kk = "";
for(int m=0; m < sub;m++){
kk += " ";
}
System.out.print(kk + res[i][j] + " ");
}
}
System.out.println();
}
}
}
</span>
运行结果裁图: