歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 逆時針輸出回形矩陣圖(Java版本)

逆時針輸出回形矩陣圖(Java版本)

日期:2017/3/1 10:10:40   编辑:Linux編程
  1. public static void main(String args[]){
  2. //逆時針輸出回形矩陣圖
  3. int[][] arr = getArray(4,4);
  4. for(int i=0;i<arr.length;i++){
  5. for(int j=0;j<arr[i].length;j++){
  6. System.out.print(arr[i][j]+",");
  7. }
  8. System.out.println();
  9. }
  10. }
  11. /**
  12. * 獲取xInt * yInt逆時針回形矩陣數組
  13. * @param xInt,矩陣x軸大小
  14. * @param yInt,矩陣y軸大小
  15. * @return
  16. */
  17. public static int[][] getArray(int xInt, int yInt){
  18. int xMax = xInt;
  19. int yMax = yInt;
  20. int n = 4;
  21. int arr[][]=new int[yMax][xMax];
  22. int x = 0, y = 0;
  23. int xMin = 0, yMin = 0;
  24. int size = xMax * yMax;
  25. boolean flag = true;
  26. for(int i=0;i<size;i++){
  27. arr[y][x] = i+1;
  28. if((y+1)<yMax && flag){
  29. y++;
  30. }else if((x+1)<xMax && flag){
  31. x++;
  32. }else {
  33. if(y>yMin){
  34. y--;
  35. }else if(x>(xMin+1)){
  36. x--;
  37. }else{
  38. xMax--;
  39. yMax--;
  40. xMin++;
  41. yMin++;
  42. y++;
  43. flag = true;
  44. }
  45. }
  46. if((y+1) == yMax && (x+1) == xMax){
  47. flag = false;
  48. }
  49. }
  50. return arr;
  51. }
Copyright © Linux教程網 All Rights Reserved