题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
解答:用标记矩阵来记录已访问的位置
public class Q_19 {
public ArrayList<Integer> printMatrix(int[][] matrix) { int sizey = matrix[0].length;//矩阵列边界 int sizex = matrix.length;//矩阵行边界 int[][] matrixChooes = new int[matrix.length][matrix[0].length];//访问标记矩阵 ArrayList<Integer> list = new ArrayList<Integer>(); int x = 0, y = 0; list.add(matrix[0][0]); matrixChooes[0][0] = 1; int direction = 1; while (true) { if (direction == 1) {//1是向右,2是向下,3是向左,4是向上 if (y < sizey - 1 && matrixChooes[x][y + 1] == 0) {//不超过边界且未被访问 list.add(matrix[x][y + 1]); matrixChooes[x][y + 1] = 1; y++; } else { if (x < sizex - 1 && matrixChooes[x + 1][y] == 0) { list.add(matrix[x + 1][y]); matrixChooes[x + 1][y] = 1; x++; direction = 2;//转向 } else { break;//若是转向后的数值也被访问,则表明所有的数已经被访问 } } } else if (direction == 2) { if (x < sizex - 1 && matrixChooes[x + 1][y] == 0) { list.add(matrix[x + 1][y]); matrixChooes[x + 1][y] = 1; x++; } else { if (y > 0 && matrixChooes[x][y - 1] == 0) { list.add(matrix[x][y - 1]); matrixChooes[x][y - 1] = 1; y--; direction = 3; } else { break; } } } else if (direction == 3) { if (y > 0 && matrixChooes[x][y - 1] == 0) { list.add(matrix[x][y - 1]); matrixChooes[x][y - 1] = 1; y--; } else { if (x > 0 && matrixChooes[x - 1][y] == 0) { list.add(matrix[x - 1][y]); matrixChooes[x - 1][y] = 1; x--; direction = 4; } else { break; } } } else if (direction == 4) { if (x > 0 && matrixChooes[x - 1][y] == 0) { list.add(matrix[x - 1][y]); matrixChooes[x - 1][y] = 1; x--; } else { if (y < sizey - 1 && matrixChooes[x][y + 1] == 0) { list.add(matrix[x][y + 1]); matrixChooes[x][y + 1] = 1; y++; direction = 1; } else { break; } } } } return list; } public static void main(String[] args) { int[][] matrix = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; int[][] matrix1 = {{}}; System.out.println(new Q_19().printMatrix(matrix)); }
}