回旋矩阵(java算法)

        最近要换份工作或者在家休息一段时间,所以练练常用的面试算法题,说是原创也不完全是。不过确实是看了算法后,自己重新实现了一遍。

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();
		}
	}

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值