螺旋矩阵(顺时针内转)

阅读更多
import java.util.Arrays;

public class SpiralMatrix {
	/**
	 * @param args
	 * @author zhangshaonian
	 */
	public static void main(String[] args) {
		int[][] base = spiralMatrix(3);
		for (int i = 0; i < base.length; i++) {
			System.out.println(Arrays.toString(base[i]));
		}

	}

	private static int[][] spiralMatrix(int num) {
		int size = num;
		int[][] m = new int[size][size];
		int circleNum = num / 2 + num % 2;//圈数
		int count = 1;
		int startX = 0;
		int startY = 0;
		for (int i = 0; i < circleNum; i++) {
			int subSize = num - 2 * i;//每个边上有多少个数
			// 计算右
			for (int j = 0; j < subSize; j++) {

				if (j == subSize - 1) {
					m[startX][startY] = count++;
					startX++;// 向下拐弯
				} else {
					m[startX][startY++] = count++;
				}

			}
			// 计算下
			for (int j = 0; j < subSize - 1; j++) {
				if (j == subSize - 2) {
					m[startX][startY] = count++;
					startY--;// 向左拐弯
				} else {
					m[startX++][startY] = count++;
				}

			}
			// 计算左
			for (int j = 0; j < subSize - 1; j++) {
				if (j == subSize - 2) {
					m[startX][startY] = count++;
					startX--;// 向上拐弯
				} else {
					m[startX][startY--] = count++;
				}

			}
			// 计算上
			for (int j = 0; j < subSize - 2; j++) {
				if (j == subSize - 3) {
					m[startX][startY] = count++;
					startY++;// 向右拐弯
				} else {
					m[startX--][startY] = count++;
				}

			}

		}
		return m;

	}
}

 

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