最近要换份工作或者在家休息一段时间,所以练练常用的面试算法题,说是原创也不完全是。不过确实是看了算法后,自己重新实现了一遍。
package com.liuliu.matrix;
public class ShunXu {
static int length = 5;
static int[][] snake = new int[length][length];
static int value = 1;
static enum Direction {
Right, Down, Left, Up;
}
public static void initialArray() {
int row = 0;
int line = 0;
Direction direction = Direction.Right;
for (int i = 0; i < length * length; i++) {
snake[row][line] = value;
direction = getDirection(row, line, direction);
switch (direction) {
case Right:
line++;
break;
case Down:
row++;
break;
case Left:
line--;
break;
case Up:
row--;
break;
}
value++;
}
}
public static Direction getDirection(int row, int line, Direction direction) {
Direction nextDirection = direction;
if (direction == Direction.Right) {
if (line == length - 1 || snake[row][line + 1] != 0)
nextDirection = Direction.Down;
} else if (direction == Direction.Down) {
if (row == length - 1 || snake[row + 1][line] != 0)
nextDirection = Direction.Left;
} else if (direction == Direction.Left) {
if (line == 0 || snake[row][line - 1] != 0)
nextDirection = Direction.Up;
} else if (direction == Direction.Up) {
if (snake[row - 1][line] != 0)
nextDirection = Direction.Right;
}
return nextDirection;
}
/**
* @param args
*/
public static void main(String[] args) {
initialArray();
// display.....
for (int i = 0; i < length; i++) {
for (int j = 0; j < length; j++) {
System.out.print(snake[i][j] + "\t");
}
System.out.println();
}
}
}