与其明天开始,不如现在行动!
文章目录
- Zigzag矩阵打印
- 1.1 题目描述
- 1.2 解决思路
- 1.3 代码实现
- 💎总结
Zigzag矩阵打印
1.1 题目描述
有一个n行m列的矩阵,要求按照Z字形打印出数据,如图:
1.2 解决思路
- 用一个指针,从a开始一直往右走,走到头再往下走
- 第二个指针,从a开始一直往下走,走到头再往右走
- 两个指针,每走一步,就打印他们之间直线上的点
1.3 代码实现
public class ZigzagPrintMatrix {public static void zigzagPrintMatrix(int[][] matrix) {if (matrix == null) {return;}// a指针int aRow = 0;int aColumn = 0;// b指针int bRow = 0;int bColumn = 0;// 向上打印还是向下打印boolean flag = true;// 矩阵边界int maxRow = matrix.length - 1;int maxColumn = matrix[0].length - 1;while (aRow != maxRow + 1) {printMatrix(matrix, aRow, aColumn, bRow, bColumn, flag);aRow = aColumn == maxColumn ? aRow + 1 : aRow;aColumn = aColumn == maxColumn ? aColumn : aColumn + 1;bColumn = bRow == maxRow ? bColumn + 1 : bColumn;bRow = bRow == maxRow ? bRow : bRow + 1;// 每次打印完要改变方向flag = !flag;}}private static void printMatrix(int[][] matrix, int aRow, int aColumn, int bRow, int bColumn, boolean flag) {if (flag) {while (bRow != aRow - 1) {System.out.print(matrix[bRow--][bColumn++] + " ");}}else {while (aRow != bRow + 1) {System.out.print(matrix[aRow++][aColumn--] + " ");}}}public static void main(String[] args) {int[][] matrix = new int[5][3];int num = 1;for (int i = 0; i < matrix.length; i++) {for (int j = 0; j < matrix[i].length; j++) {matrix[i][j] = num++;}}zigzagPrintMatrix(matrix);}
}
💎总结
本文中若是有出现的错误请在评论区或者私信指出,我再进行改正优化,如果文章对你有所帮助,请给博主一个宝贵的三连,感谢大家😘!!!