“之”字形打印矩阵~
編程如下:
歡迎大家前來討論~
public class PrintMatirx {
public static void main(String args[]) {
int arr[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };
printZigMatrix(arr);
}
public static void printZigMatrix(int arr[][]) {
int row1 = 0;
int col1 = 0;
int row2 = 0;
int col2 = 0;
int helpR = arr.length - 1;
int helpC = arr[0].length - 1;
boolean dir = false;
/* 下面是來判斷(row1,col1)點(diǎn)是往右方移動(dòng)還是往下邊移動(dòng),當(dāng)col1 == helpC時(shí),就要往下面移動(dòng)了,下面同理 */
while (row1 <= helpR) {// 什么時(shí)候停止對(duì)角線遍歷呢?當(dāng)row > helpR時(shí),說明已經(jīng)遍歷到底部了,就可以停止遍歷了
printDiagonal(arr, row1, col1, row2, col2, dir);
if (col1 == helpC) {
row1++;
} else {
col1++;
}
if (row2 == helpR) {
col2++;
} else {
row2++;
}
dir = !dir;// 方向每次都調(diào)轉(zhuǎn)一次
}
}
/* 按照對(duì)角線方向打印出矩陣的元素,因?yàn)槭侵中?#xff0c;所以要定義一個(gè)標(biāo)志dir來使其一次往右上方打印,一次往左下方打印 */
public static void printDiagonal(int arr[][], int row1, int col1, int row2, int col2, boolean dir) {
if (dir) {
while (row1 <= row2) {// 打印停止的判斷:row1 <= row2的時(shí)候,可以繼續(xù)往下打印,當(dāng)row1 > row2時(shí),停止打印,下面也是同理
System.out.print(arr[row1++][col1--] + " ");// 怎么做到往對(duì)角線打印,可以通過row++同時(shí)col--來實(shí)現(xiàn)
}
} else {
while (row2 >= row1) {
System.out.print(arr[row2--][col2++] + " ");
}
}
}
}
總結(jié)
以上是生活随笔為你收集整理的“之”字形打印矩阵~的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 权限验证框架Shiro
- 下一篇: spring源码分析第一天------源