目標(biāo):
將一個二維數(shù)組按順時針輸出。
(推薦教程:java入門)
代碼實現(xiàn)如下:
public class 順時針輸出二維矩陣 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int[][]arr={ {1,2,2,3}, {4,5,4,6}, {7,8,6,9}, {1,2,3,4} }; int k=0; for(int i = 0; i < arr.length;i++){ for(int j = 0;j < arr[0].length;j++){ k++; System.out.print(arr[i][j]+" "); if(k % 4 == 0){ System.out.println(""); } } } System.out.println(""); System.out.println(arr[0].length);//列數(shù) System.out.println(arr.length);//行數(shù) print(arr); } static void print (int[][]arr){ int leftUpRow = 0;//最左行 int leftUpCol = 0;//最左列 int rightDownRow = arr.length-1;//最右列 int rightDownCol = arr[0].length-1;//最右列 while(leftUpRow <= rightDownRow && leftUpCol <= rightDownCol){ int row = leftUpRow, col = leftUpCol; //矩陣的第一行,此時行不變,列++ while(col <= rightDownCol){ System.out.print(arr[row][col++]+" "); } //矩陣右邊第一列 此時行++,列不變 //將 col,row 恢復(fù) col = rightDownCol; row++; while(row <= rightDownRow){ System.out.print(arr[row++][col]+" "); } //矩陣的最下面一行 此時 行不變 列-- //還需要恢復(fù) col row 的值 row = rightDownRow; col--; while(col >= leftUpCol){ System.out.print(arr[row][col--]+" "); } //矩陣最左邊一列,此時行--,列不變 //繼續(xù)恢復(fù) col row的值 col = leftUpCol; row--; while(row > leftUpRow){ System.out.print(arr[row--][col]+" "); } leftUpRow++; leftUpCol++; rightDownRow--; rightDownCol--; } } }
輸出結(jié)果:
1 2 2 3 4 5 4 6 7 8 6 9 1 2 3 4 1 2 2 3 6 9 4 3 2 1 7 4 5 4 6 8
相關(guān)視頻教程推薦:java視頻