题解 | #顺时针打印矩阵#
顺时针打印矩阵
https://www.nowcoder.com/practice/9b4c81a02cd34f76be2659fa0d54342a
import java.util.ArrayList; public class Solution { public ArrayList<Integer> printMatrix(int [][] matrix) { int col = matrix[0].length; ArrayList<Integer> list = new ArrayList<>(); String dir = "右"; if (col == 0 && matrix.length == 1) { // 应付搞破坏代码 return list; } int count = 0; int i = 0; int j = 0; list.add(matrix[0][0]); matrix[i][j] = -1; while (count < 4) { if ("右".equals(dir)) { if (j + 1 == col || matrix[i][j + 1] == -1) { dir = get(dir); count++; } else { list.add(matrix[i][j + 1] ); System.out.println("向右遍历到" + matrix[i][j + 1]); matrix[i][j + 1] = -1; j = j + 1; count = 0; } } else if ("下".equals(dir)) { if (i + 1 == matrix.length || matrix[i + 1][j] == -1) { dir = get(dir); count ++; } else { list.add(matrix[i + 1][j] ); System.out.println("向下遍历到" + matrix[i + 1][j]); matrix[i + 1][j] = -1; i = i + 1; count = 0; } } else if ("上".equals(dir)) { if (i == 0 || matrix[i - 1][j] == -1) { dir = get(dir); count ++; } else { list.add(matrix[i - 1][j] ); System.out.println("向上遍历到" + matrix[i - 1][j]); matrix[i - 1][j] = -1; i = i - 1; count = 0; } } else if ("左".equals(dir)) { if (j == 0 || matrix[i][j - 1] == -1) { dir = get(dir); count ++; } else { list.add(matrix[i][j - 1] ); System.out.println("向左遍历到" + matrix[i][j - 1]); matrix[i][j - 1] = -1; j = j - 1; count = 0; } } } return list; } public static String get(String lastdir) { String dir = lastdir; if ("上".equals(lastdir)) { return "右"; } if ("右".equals(lastdir)) { return "下"; } if ("下".equals(lastdir)) { return "左"; } if ("左".equals(lastdir)) { return "上"; } return null; } }