生活随笔
收集整理的這篇文章主要介紹了
方欣科技算法面试:蛇形矩阵2
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1 題目描述
/**
?* 蛇形矩陣2
?*?
?* 輸入4
?*?
?* 輸出
?* ?1 12 11 10
?* ?2 13 16 9
?* ?3 14 15 8
?* ?4 5 6 7
?*?
?*?
?* */
2 ?java代碼
package 公司面試.方欣科技;/*** 蛇形矩陣2* * 輸入4* * 輸出* 1 12 11 10* 2 13 16 9* 3 14 15 8* 4 5 6 7* * * */public class SnakeMatrix2 {public void snakeMatrix2(int n){if(n < 1){System.out.println("請輸入一個大于0的整數");return ; }int row=-1; // 矩陣橫坐標int col=0; // 矩陣縱坐標int counter = 0; //計數器int[][] array = new int[n][n];//初始化矩陣int direction = 0; // direction 為方向 (0 向下 , 1 向右, 2 向上 , 3 向左)while( counter < n*n){counter++;//向下if( direction==0 && row+1 < n && array[row+1][col] ==0 ){row++;if(row==n-1 || array[row+1][col] !=0){direction = 1; }}//向右else if(direction==1 && col+1 < n && array[row][col+1] ==0 ){col++;if(col==n-1 || array[row][col+1] !=0){direction = 2; }}//向上else if(direction==2 && row-1 >= 0 && array[row-1][col] ==0 ){row--;if(row==0 || array[row-1][col] !=0){direction = 3; }}//向左else if(direction==3 && col-1 >= 0 && array[row][col-1] ==0 ){col--;if(col==0 || array[row][col-1] !=0){direction = 0; }}array[row][col] = counter;}this.show(array);}private void show(int v[][]){if(v==null||v.length==0) return ;for(int i = 0 ; i < v.length ; i++){if(i!=0) System.out.println();for(int j = 0 ; j < v.length ; j++){System.out.print(v[i][j]+" ");}}}public static void main(String args[]){SnakeMatrix2 snakeMatrix = new SnakeMatrix2();snakeMatrix.snakeMatrix2(5);}
}
3 輸出結果
總結
以上是生活随笔為你收集整理的方欣科技算法面试:蛇形矩阵2的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。