Java笔试题:顺时针方向输出n*m的矩阵

题目描述:给定两个正整数n和m,代表n行m列,将数字0-n*m-1按顺时针方向旋转填入n*m的矩阵并输出

例如:n=4 m=5

 0   1   2   3  4

13 14 15 16 5

12 19 18 17 6

11 10  9   8  7

窍门就是遇到墙角就转弯

public class InverseMatrix {

	static final int UP = 0;
	static final int RIGHT = 1;
	static final int DOWN = 2;
	static final int LEFT = 3;

	public static void main(String[] args) {
		int n = 4;
		int m = 5;
		fill(n, m);
	}

	public static void fill(int n, int m) {
		//待填入的数组
		int[][] d = new int[n][m];
		//标记每个位置是否填入数字
		boolean[][] flag = new boolean[n][m];
		//当前应该要填入的值
		int cur = 1;
		//y为纵坐标(上下方向),x为横坐标(左右方向)
		int x = 0, y = 0;
		//默认方向向右走
		int di = RIGHT;
		//0,0这个位置不用填,本来就是0
		flag[0][0] = true;
		while (cur < n * m) {
			//判断这一步应该往哪走
			di = judgeDi(y, m, x, n, flag, di);
			switch (di) {
			case RIGHT:
				x++;
				break;
			case DOWN:
				y++;
				break;
			case LEFT:
				x--;
				break;
			case UP:
				y--;
				break;
			}
			//填值,并把当前位置标记为已填
			d[y][x] = cur++;
			flag[y][x] = true;
		}

		for (int k = 0; k < n; k++) {
			for (int h = 0; h < m; h++) {
				System.out.print(d[k][h] + " ");
			}
			System.out.println();
		}
	}
	

	/**
	 * 判断方向
	 */
	private static int judgeDi(int y, int m, int x, int n, boolean[][] flag, int preDi) {
		int di = preDi;
		if (di == RIGHT && (x == m - 1 || (x + 1 < m && flag[y][x + 1]))) {
			// 碰到右上角的墙,往下转弯
			di = DOWN;
		} else if (di == DOWN && (y == n - 1 || (y + 1 < n && flag[y + 1][x]))) {
			// 碰到右下角的墙,向左转弯
			di = LEFT;
		} else if (di == LEFT && (x == 0 || (x - 1 >= 0 && flag[y][x - 1]))) {
			// 碰到左下角的墙,向上转弯
			di = UP;
		} else if (di == UP && (y == 0 || (y - 1 >= 0 && flag[y - 1][x]))) {
			// 碰到左上角的墙,向右转弯
			di = RIGHT;
		}
		return di;
	}

}

 

你可能感兴趣的:(Java笔试题:顺时针方向输出n*m的矩阵)