`
/** * 蛇形矩阵是指一个呈螺旋状的矩阵,它的数字由第一行开始到右边不断变大,向下变大, 向左变大,向上变大,如此循环。 * @author lhever 2017年4月4日 下午3:24:47 * @version v1.0 */ public class SnakePrint { private int size = 0; private int value = -1; private int[][] snake = null; private Direction nextDirection = null; static enum Direction { Right, Down, Left, Up } /** * 构造函数,在构造中完成初始化和蛇形数组的计算 * * @param size * @author lhever 2017年4月4日 下午2:37:32 * @since v1.0 */ public SnakePrint(int size) { if (size <= 0) { throw new IllegalArgumentException("size 必须是一个正整数"); } this.size = size; this.snake = new int[size][size]; this.value = 1; nextDirection = Direction.Right; initArray(); } /** * 计算蛇形数组 * * @author lhever 2017年4月4日 下午2:38:15 * @since v1.0 */ public void initArray() { int row = 0, col = 0; for (int i = 0; i < size * size; i++) { snake[row][col] = value; nextDirection = judgeDirection(row, col); switch (nextDirection) { case Right: col++; break; case Down: row++; break; case Left: col--; break; case Up: row--; break; default: System.out.println("error"); } value++; } } /** * 私有方法,用于判断位置(row, col)的下一个位置所处方向 * * @param row * @param col * @return * @author lhever 2017年4月4日 下午2:38:36 * @since v1.0 */ private Direction judgeDirection(int row, int col) { Direction direction = this.nextDirection; switch (direction) { case Right: if ((col == size - 1) || (snake[row][col + 1] != 0)) { direction = Direction.Down; } break; case Down: if ((row == size - 1) || (snake[row + 1][col] != 0)) { direction = Direction.Left; } break; case Left: if ((col == 0) || snake[row][col - 1] != 0) { direction = Direction.Up; } break; case Up: if (snake[row - 1][col] != 0) { direction = Direction.Right; } break; } return direction; } /** * 打印出蛇形数组 * * @author lhever 2017年4月4日 下午2:41:51 * @since v1.0 */ public void printSnake() { for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { System.out.printf("]", snake[i][j]); } System.out.println(); } } public static void main(String... args) { SnakePrint s = new SnakePrint(8); s.printSnake(); System.out.println(); SnakePrint s1 = new SnakePrint(20); s1.printSnake(); } }