# 顺时针打印矩阵

2016/08/17 10:29

• 输入一个矩阵，按照从外向里以顺时针的顺序依次打印出每一个数字，例如，如果输入如下矩阵： 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.
• 注意一些细节即可，代码如下：
import java.util.ArrayList;
import java.util.List;
public class Solution {
public ArrayList<Integer> printMatrix(int[][] matrix) {
ArrayList<Integer> list = new ArrayList<Integer>();
if (matrix.length == 0 && matrix[0].length == 0)
return list;
int direction[][] = new int[][] { { 0, 1 }, { 1, 0 }, { 0, -1 },
{ -1, 0 } };
int mark[][] = new int[matrix.length][matrix[0].length];
printMatrixRecur(matrix, mark, 0, direction, 0, 0, list);
return list;
}
void printMatrixRecur(int[][] matrix, int[][] mark, int dirct,int[][] direction, int x, int y, List<Integer> list) {
if (mark[x][y] == 0) {
mark[x][y] = 1;
}
for (int i = 0; i < 4; ++i) {
int j = (dirct + i) % 4;
int dx = x + direction[j][0];
int dy = y + direction[j][1];
if (dx >= 0 && dx < matrix.length && dy >= 0
&& dy < matrix[0].length && mark[dx][dy] == 0)
printMatrixRecur(matrix, mark, j, direction, dx, dy, list); //direc在下一次递归中直接加上1标识下一个方向
}
}
}


0
0 收藏

0 评论
0 收藏
0