回旋矩阵

在JavaEye上看到一个支付宝的笔试题,是关于回旋矩阵的,题目如下:
输入一个矩阵的行列数量,生成一个螺旋矩阵,比如输入5,则打印:
25 24 23 22 21
10  9  8  7 20
11  2  1  6 19
12  3  4  5 18
13 14 15 16 17

输入3,则打印:
9  8  7
2  1  6
3  4  5


package cn.wingware;

public class ConvoluteNumber {

	public static void main(String args[]) {

		int a = 10;

		int aa[][] = new int[a][a];
		int p[];
		for (int i = a * a; i >= 1; i--) {
			p = getCoordinateByIndex(i, a);
			aa[p[0]][p[1]] = i;
		}
		for (int i = 0; i < a; i++) {
			for (int j = 0; j < a; j++) {
				System.out.print(aa[j][i] + "\t");
			}
			System.out.println("");
		}

	}

	/**
	 * 获取总数
	 * 
	 * @param count
	 * @return
	 */
	private static int getAllCountFor(int count) {
		return count * count;
	}

	/**
	 * 获取
	 * 
	 * @param count
	 * @return
	 */
	private static int getCount(int count) {
		if (count < 1) {
			throw new RuntimeException("数字应该在大于0.");
		}
		if (count == 1) {
			return 1;
		}
		return count * 4 - 4;
	}

	/**
	 * 获取坐标轴
	 * 
	 * @param index
	 *            第几位数
	 * @param count
	 *            输入量
	 * @return
	 */
	public static int[] getCoordinateByIndex(int index, int count) {
		if (index <= 0 || index > getAllCountFor(count)) {
			throw new RuntimeException("数字应该在[0," + (getAllCountFor(count) - 1) + "]");
		}
		int t = count;
		int temp = count;
		for (int i = count; i >= 1; i = i - 2) {
			int tt = getAllCountFor(i);
			t = i;
			if (tt >= index && index > tt - getCount(i)) {
				break;
			}
			temp--;
		}
		int begin = count - temp;
		/** 起点坐标 */
		// int x = 0, y = 0;
		/** 偏移量 */
		int a = begin, b = begin;
		int _begin = getAllCountFor(t) - getCount(t);
		if ((_begin + (t - 1) * 4) >= index && index > (_begin + (t - 1) * 3)) {
			a = (_begin + (t - 1) * 4) - index + begin;
		} else if ((_begin + (t - 1) * 3) >= index && index > (_begin + (t - 1) * 2)) {
			a = count - begin - 1;
			b = (_begin + (t - 1) * 3) - index + begin;
		} else if ((_begin + (t - 1) * 2) >= index && index > (_begin + (t - 1) * 1)) {
			a = count - ((_begin + (t - 1) * 2) - index) - begin - 1;
			b = count - begin - 1;
		} else if ((_begin + (t - 1) * 1) >= index) {
			b = index - (_begin + (t - 1) * 1) + count - begin - 1;
		}
		return new int[] { a, b };
	}

}




小弟不才,写了好大功夫。。。
哎!~正的是老了。

你可能感兴趣的:(J#)