题目:输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 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.
思路:用一个标记矩阵记录走过的点。有四种走的可能方向:
Right: if I can go right and go down, I go right; (Or if I can only go right.)
Down: if I can go down and go left, I go down; (Or if I can only go down.)
Left: if I can go left and go up, I go left; (Or if I can only go left.)
Up: if I can go up and go right, I go up; (Or if I can only go up.)
我们只需要解决当向右可走时的冲突,当向右可走时,如果向上可走,我向上走;否则,我向右走。代码如下:
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> printMatrix(int[][] matrix) {
ArrayList<Integer> array = new ArrayList<Integer>();
int m = matrix.length;
if(m==0) return array;
int n = matrix[0].length;
if(n==0) return array;
boolean[][] mark = new boolean[m][n];
for(int i=0; i<m; i++)
for(int j=0; j<n; j++)
mark[i][j] = false;
boolean done = false;
int current = matrix[0][0];
array.add(current);
mark[0][0] = true;
int i=0, j=0;
while(!done) {
if(j+1<n && mark[i][j+1]==false) { // I can go right
// If I can go up, I go up
if(i-1>=0 && mark[i-1][j]==false) {
array.add(matrix[i-1][j]);
mark[i-1][j] = true;
i = i-1;
}
else { // Otherwise, go down
array.add(matrix[i][j+1]);
mark[i][j+1] = true;
j = j + 1;
}
}
else if(i+1<m && mark[i+1][j]==false) { // I can go down
// If I can go right, I've gone right; so I can only go down
array.add(matrix[i+1][j]);
mark[i+1][j] = true;
i = i+1;
}
else if(j-1>=0 && mark[i][j-1]==false) { // I can go left
// If I can go down, I've already gone down; so I can only go left
array.add(matrix[i][j-1]);
mark[i][j-1] = true;
j = j-1;
}
else if(i-1>=0 && mark[i-1][j]==false) { // I can go up
// If I can go left, I've already gone left; so I can only go up
array.add(matrix[i-1][j]);
mark[i-1][j] = true;
i = i-1;
}
else
done = true;
}
return array;
}
}