剑指Offer--顺时针打印矩阵
题目输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下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.
思路 我的思路是,分析矩阵打印的特点,一条“蛇”形,大体上是右、下、左、上这样的趋势进行遍历,我这里是将遍历过的都重置为-1进行记录;
自己写的Low代码
import java.util.ArrayList;
public class Solution11 {
public static ArrayList<Integer> printMatrix(int[][] matrix) {
ArrayList<Integer> list = new ArrayList<Integer>();
if (matrix == null || matrix.length == 0) {
return list;
}
// 右、下、左、上;
// int start = matrix[0][0];
int flag = 0;// 0表示右,1表示下移,2表示左移,3表示上移,记录上一次的朝向;
int startR = 0;
int startC = 0;
int rows = matrix.length;// 行数;
int cols = matrix[0].length;// 列数;
// 总长度;
int count = rows * cols;
while (count != 0) { // 所有的数都遍历到了;
if(matrix[startR][startC]!=-1) { //这里要在判断一下;否则上移的时候回出错;
list.add(matrix[startR][startC]);
matrix[startR][startC] = -1;// 已经遍历的就用-1表示;
count--;// 减少一个;
}
// 控制方向;
if (flag == 0) {
if (startC + 1 < cols && matrix[startR][startC + 1] != -1) { // 右移;
startC++;
} else {// 转变方向;
flag = 1;
}
}
if (flag == 1) {
if (startR + 1 < rows && matrix[startR + 1][startC] != -1) {// 下移;
startR++;
} else {
flag = 2;
}
}
if (flag == 2) {
if (startC - 1 >= 0 && matrix[startR][startC - 1] != -1) { // 左移
startC--;
} else {
flag = 3;
}
}
if (flag == 3) {
if (startR - 1 >= 0 && matrix[startR - 1][startC] != -1) {// 上移;
startR--;
} else {
flag = 0;
}
}
}
return list;
}
public static void main(String[] args) {
int[][] matrix = { { 1, 2 }, { 3, 4 } };
System.out.println(printMatrix(matrix));
}
}
多思考,多尝试。