回形打印+螺旋形打印
一、故事背景
从前有一个叫“SJ第二阶段活动群”的qq群,本来是Google中国举办的StudyJams活动的第二阶段的讨论群,现在变成了一个生活知识分享、程序员社交、未老先衰自称人老养老群。里面有一只叫“老斯基”的老司机,天天带我们开火车。偶尔讲授一下姿势。今天突发奇想,出了这么一道题。引得群友纷纷po图炫耀(“垃圾算法,随手捏来”、“太简单,没挑战”、“斯基,我来虐你”)。没错,我就是群友。
二、代码
1、回形
import java.util.Arrays;
import java.util.Scanner;
/**
* 回形
* Created by Relish on 2016/8/8.
*/
public class 回形 {
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
int n = cin.nextInt();
int[][] map = new int[n * 2 - 1][n * 2 - 1];
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[i].length; j++) {
int d1 = Math.abs(i - n + 1);
int d2 = Math.abs(j - n + 1);
map[i][j] = 1 + (d1 > d2 ? d1 : d2);
}
}
for (int[] ints : map) {
System.out.println(Arrays.toString(ints).replaceAll("\\[|\\]|,", ""));
}
}
}
2、螺旋形
import java.util.Scanner;
/**
* 螺旋形
* Created by Relish on 2016/8/8.
*/
public class 螺旋形 {
private static final int U = 0, D = 1, L = 2, R = 3;
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
int n = cin.nextInt();
int[][] map = new int[n][n];
int x = 0, y = 0, dir = R;
for (int i = 1; i <= n * n; i++) {
map[x][y] = i;
switch (dir) {
case U:
if (x - 1 < 0 || map[x - 1][y] != 0) {
dir = R;
y++;
} else {
x--;
}
break;
case D:
if (x + 1 > n - 1 || map[x + 1][y] != 0) {
dir = L;
y--;
} else {
x++;
}
break;
case L:
if (y - 1 < 0 || map[x][y - 1] != 0) {
dir = U;
x--;
} else {
y--;
}
break;
case R:
if (y + 1 > n - 1 || map[x][y + 1] != 0) {
dir = D;
x++;
} else {
y++;
}
break;
}
}
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[i].length; j++) {
System.out.print(String.format("%2d ", map[i][j]));
}
System.out.println();
}
}
}