是道老题了。凭着印象写,代码技巧是:先判断,后移动。
public class Snake {
static int[][] arr;
public static void print(int x, int y) {
arr = new int[x][y];
final int key = x * y;
int i = 0;
int j = -1;
int cnt = 1;
while (cnt <= key) {
while (j + 1 < y && arr[i][j + 1] == 0) {
arr[i][++j] = cnt++;
}
while (i + 1 < x && arr[i + 1][j] == 0) {
arr[++i][j] = cnt++;
}
while (j - 1 >= 0 && arr[i][j - 1] == 0) {
arr[i][--j] = cnt++;
}
while (i - 1 >= 0 && arr[i - 1][j] == 0) {
arr[--i][j] = cnt++;
}
}
for (int k = 0; k < arr.length; k++) {
System.out.println(Arrays.toString(arr[k]));
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt()) {
int x = scanner.nextInt();
int y = scanner.nextInt();
print(x, y);
}
}
}










网友评论