Advertisement
valitomi

Untitled

May 1st, 2021
14
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.75 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class Main {
  4.  
  5. public static void main(String[] args) {
  6. Scanner sc = new Scanner(System.in);
  7. int m = sc.nextInt();
  8. int[][] matrix = new int[m][m];
  9. int position = 1;
  10. int col = 0;
  11. int row = 0;
  12.  
  13.  
  14. while (position < m * m) {
  15.  
  16. matrix[col][row] = position;
  17. if (col - 2 >= 0 && row - 1 >= 0 && matrix[col - 2][row - 1] == 0) {
  18. col -= 2;
  19. row -= 1;
  20. position++;
  21. continue;
  22. }
  23. if (col - 2 >= 0 && row + 1 < matrix.length && matrix[col - 2][row + 1] == 0) {
  24. col -= 2;
  25. row += 1;
  26. position++;
  27. continue;
  28. }
  29. if (col - 1 >= 0 && row - 2 >= 0 && matrix[col - 1][row - 2] == 0) {
  30. col -= 1;
  31. row -= 2;
  32. position++;
  33. continue;
  34. }
  35. if (col - 1 >= 0 && row + 2 < matrix.length && matrix[col - 1][row + 2] == 0) {
  36. col -= 1;
  37. row += 2;
  38. position++;
  39. continue;
  40. }
  41. if (col + 1 < matrix.length && row - 2 >= 0 && matrix[col + 1][row - 2] == 0) {
  42. col += 1;
  43. row -= 2;
  44. position++;
  45. continue;
  46. }
  47. if (col + 1 < matrix.length && row + 2 < matrix.length && matrix[col + 1][row + 2] == 0) {
  48. col += 1;
  49. row += 2;
  50. position++;
  51. continue;
  52. }
  53. if (col + 2 < matrix.length && row - 1 >= 0 && matrix[col + 2][row - 1] == 0) {
  54. col += 2;
  55. row -= 1;
  56. position++;
  57. continue;
  58. }
  59. if (col + 2 < matrix.length && row + 1 < matrix.length && matrix[col + 2][row + 1] == 0) {
  60. col += 2;
  61. row += 1;
  62. position++;
  63. continue;
  64.  
  65. } else {
  66. int a=0;
  67. for (int i = 0; i < m; i++) {
  68. for (int j = 0; j < m; j++) {
  69.  
  70. if (matrix[i][j] == 0&&a==0) {
  71. a++;
  72. position++;
  73. matrix[i][j] = position;
  74. col=i;
  75. row=j;
  76.  
  77. }
  78. }
  79. }
  80. }
  81.  
  82. }
  83. for (int i = 0; i < m; i++) {
  84. for (int j = 0; j < m; j++) {
  85. System.out.print(matrix[i][j] + " ");
  86. }
  87. System.out.println();
  88.  
  89. }
  90. }
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement