Advertisement
Mishakis

HorsePath

Nov 24th, 2018
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.65 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class Main {
  4.  
  5.     public static void main(String[] args) {
  6.         Scanner scanner = new Scanner(System.in);
  7.  
  8.         int n = scanner.nextInt();
  9.  
  10.         int[][] matrix = new int[n][n];
  11.  
  12.         int[] dirRows = {-2, -2, -1, -1, +1, +1, +2, +2};
  13.         int[] dirCols = {-1, +1, -2, +2, -2, +2, -1, +1};
  14.  
  15.         int counter = 1;
  16.  
  17.         for (int row = 0; row < matrix.length; row++) {
  18.             for (int col = 0; col < matrix[0].length; col++) {
  19.                
  20.                 int currentRow = row;
  21.                 int currentCol = col;
  22.  
  23.                 while (matrix[currentRow][currentCol] == 0) {
  24.                     matrix[currentRow][currentCol] = counter;
  25.                     counter++;
  26.  
  27.                     for (int dir = 0; dir < dirRows.length; dir++) {
  28.                         int nextRow = currentRow + dirRows[dir];
  29.                         int nextCol = currentCol + dirCols[dir];
  30.  
  31.                         if (nextRow < 0 || nextRow >= matrix.length || nextCol < 0 || nextCol >= matrix.length) {
  32.                             continue;
  33.                         }
  34.  
  35.                         if (matrix[nextRow][nextCol] != 0) {
  36.                             continue;
  37.                         }
  38.  
  39.                         currentRow = nextRow;
  40.                         currentCol = nextCol;
  41.                         break;
  42.                     }
  43.                 }
  44.             }
  45.  
  46.         }
  47.  
  48.         for(int[] row : matrix){
  49.             String result = "";
  50.             for (int cell: row) {
  51.                 result += cell + " ";
  52.             }
  53.             System.out.println(result);
  54.         }
  55.  
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement