之字形列印矩陣
阿新 • • 發佈:2018-12-14
初始化兩個座標點,一個每次向右,到達盡頭往下;一個每次向下,到達盡頭往右;列印兩點之間的對角線
public static void zigzag(int[][] arr){ if(arr==null){ return; } int ar = 0,ac = 0,br = 0,bc = 0; int rl = arr.length-1; int cl = arr[0].length-1; boolean flag = false; while(ar!=rl+1){ zPrint(arr,ar,ac,br,bc,flag); ar = ac == cl ? ++ar:ar; ac = ac == cl ? ac:++ac; bc = br == rl ? ++bc:bc; br = br == rl ? br:++br; flag = !flag; } } public static void zPrint(int[][] arr,int ar,int ac,int br,int bc,boolean flag){ if(flag){ while(ar != br+1){ System.out.print(arr[ar++][ac--]+","); } }else{ while(br!=ar-1){ System.out.print(arr[br--][bc++]+","); } } }