Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class Main {
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- int m = sc.nextInt();
- int[][] matrix = new int[m][m];
- int position = 1;
- int col = 0;
- int row = 0;
- while (position < m * m) {
- matrix[col][row] = position;
- if (col - 2 >= 0 && row - 1 >= 0 && matrix[col - 2][row - 1] == 0) {
- col -= 2;
- row -= 1;
- position++;
- continue;
- }
- if (col - 2 >= 0 && row + 1 < matrix.length && matrix[col - 2][row + 1] == 0) {
- col -= 2;
- row += 1;
- position++;
- continue;
- }
- if (col - 1 >= 0 && row - 2 >= 0 && matrix[col - 1][row - 2] == 0) {
- col -= 1;
- row -= 2;
- position++;
- continue;
- }
- if (col - 1 >= 0 && row + 2 < matrix.length && matrix[col - 1][row + 2] == 0) {
- col -= 1;
- row += 2;
- position++;
- continue;
- }
- if (col + 1 < matrix.length && row - 2 >= 0 && matrix[col + 1][row - 2] == 0) {
- col += 1;
- row -= 2;
- position++;
- continue;
- }
- if (col + 1 < matrix.length && row + 2 < matrix.length && matrix[col + 1][row + 2] == 0) {
- col += 1;
- row += 2;
- position++;
- continue;
- }
- if (col + 2 < matrix.length && row - 1 >= 0 && matrix[col + 2][row - 1] == 0) {
- col += 2;
- row -= 1;
- position++;
- continue;
- }
- if (col + 2 < matrix.length && row + 1 < matrix.length && matrix[col + 2][row + 1] == 0) {
- col += 2;
- row += 1;
- position++;
- continue;
- } else {
- int a=0;
- for (int i = 0; i < m; i++) {
- for (int j = 0; j < m; j++) {
- if (matrix[i][j] == 0&&a==0) {
- a++;
- position++;
- matrix[i][j] = position;
- col=i;
- row=j;
- }
- }
- }
- }
- }
- for (int i = 0; i < m; i++) {
- for (int j = 0; j < m; j++) {
- System.out.print(matrix[i][j] + " ");
- }
- System.out.println();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement