package bupt.syh;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
String inputStr = in.nextLine();
if (inputStr.length() == 0) {
System.out.println(0);
continue;
}
int n = Integer.parseInt(inputStr);
if (n == 0) {
System.out.println(0);
continue;
}
int[][] mat = new int[n][n];
int x = 0;
int y = 0;
int count = 1;
mat[x][y] = count++;
for (int i = 0; i < (n + 1) / 2; i++) {
while (canRight(x, y, mat)) {
mat[x][++y] = count++;
}
while (canDown(x, y, mat)) {
mat[++x][y] = count++;
}
while (canLeft(x, y, mat)) {
mat[x][--y] = count++;
}
while (canUp(x, y, mat)) {
mat[--x][y] = count++;
}
}
// 输出
for (int i = 0; i < n; i++) {
StringBuilder builder = new StringBuilder();
for (int j = 0; j < n; j++) {
builder.append(mat[i][j] + " ");
}
System.out.println(builder.toString().trim());
}
}
}
public static boolean canUp(int x, int y, int[][] mat) {
if (x == 0) {
return false;
}
if (mat[x - 1][y] != 0) {
return false;
}
return true;
}
public static boolean canDown(int x, int y, int[][] mat) {
if (x == mat.length - 1) {
return false;
}
if (mat[x + 1][y] != 0) {
return false;
}
return true;
}
public static boolean canLeft(int x, int y, int[][] mat) {
if (y == 0) {
return false;
}
if (mat[x][y - 1] != 0) {
return false;
}
return true;
}
public static boolean canRight(int x, int y, int[][] mat) {
if (y == mat.length - 1) {
return false;
}
if (mat[x][y + 1] != 0) {
return false;
}
return true;
}
}
[2016腾讯暑期实习在线笔试题][蛇形矩阵]
最新推荐文章于 2024-04-22 19:01:47 发布