LeetCode54.螺旋矩阵

使用递归,但效率很低

class Solution {
	public List<Integer> spiralOrder(int[][] matrix) {
		if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
			return new ArrayList<>();
		ArrayList<Integer> reseult = new ArrayList<>(matrix.length * matrix[0].length);
		dfs(0, 0, matrix, new boolean[matrix.length][matrix[0].length], reseult);
		return reseult;
	}

	public void dfs(int x, int y, int[][] matrix, boolean[][] over, ArrayList<Integer> reseult) {
		if (check(x, y, matrix, over)) {
			over[x][y] = true;
			reseult.add(matrix[x][y]);
			dfs(x, y + 1, matrix, over, reseult);
			dfs(x + 1, y, matrix, over, reseult);
			dfs(x, y - 1, matrix, over, reseult);
			xdown(x - 1, y, matrix, over, reseult);
		}
	}

	public boolean check(int x, int y, int[][] matrix, boolean[][] over) {
		if ((x | y | (matrix.length - x - 1) | (matrix[0].length - y - 1)) < 0 || over[x][y])
			return false;
		return true;
	}

	public void xdown(int x, int y, int[][] matrix, boolean[][] over, ArrayList<Integer> reseult) {
		while (check(x - 1, y, matrix, over)) {
			over[x][y] = true;
			reseult.add(matrix[x][y]);
			--x;
		}
		dfs(x, y, matrix, over, reseult);
	}
}

猜你喜欢

转载自blog.csdn.net/wuwang01/article/details/86691987