用双指针的方法蛇形打印矩阵
示意图:
所以蛇形打印的顺序可以看作两个指针的同时移动,每次需要打印的内容就是两个只针对角线上所对应的内容,每移动一次打印的方向就改变一次,直到任意一个起点移动到最后一个顶点的位置。
package chap1;
/**
* @author your_tt
* @date 2021年05月25日16:19
*/
public class Serpentine_matrix {
public static void serpentine(int[][] matrix) {
//a代表先向右移动的指针,b代表先向下移动的指针
int ax = 0;
int ay = 0;
int bx = 0;
int by = 0;
int endx = matrix.length - 1;
int endy = matrix[0].length - 1;
boolean fromUp = false;
while (ax <= endx) {
printLevel(matrix, ax, ay, bx, by, fromUp);
ax = ay == endy ? ax + 1 : ax;
ay = ay == endy ? ay : ay + 1;
//这里必须注意移动坐标变换的顺序,b向下移动,在没有到达endx前改变的是纵坐标,所以应当是先对by进行坐标判断,否则会出现下标越界的情况!
by = bx == endx ? by + 1 : by;
bx = bx == endx ? bx : bx + 1;
fromUp = !fromUp;
}
}
public static void printLevel(int[][] m, int ax, int ay, int bx, int by, boolean f) {
if (f) {//上到下
while (ay >= by) {
System.out.print(m[ax++][ay--] + " ");
}
} else {//下到上
while (ax <= bx) {
System.out.print(m[bx--][by++] + " ");
}
}
}
public static void main(String[] args) {
//测试数据
int[][] matrix = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
serpentine(matrix);
}
}