Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.company;
- import java.util.Scanner;
- public class Main {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- int N = Integer.parseInt(scanner.nextLine());
- int moves = N * N;
- int[][] chessBoard = new int[N][N];
- for (int row = 0; row < N; row++) {
- for (int col = 0; col < N; col++) {
- chessBoard[row][col] = 0;
- }
- }
- int startPosition = chessBoard[0][0];
- chessBoard[0][0] = 1;
- int moveRow = 0;
- int moveCol = 0;
- int right = 0;
- for (int row = 0; row < chessBoard.length; row++) {
- for (int col = 0; col < chessBoard[row].length; col++) {
- for (int i = 2; i <= moves; i++) {
- if (row - 2 >= 0 && col - 1 >= 0) {
- if (chessBoard[row - 2][col - 1] == 0) {
- chessBoard[row - 2][col - 1] = i;
- row -= 2;
- col -= 1;
- continue;
- }
- }
- if (row - 2 >= 0 && col + 1 < N) { ;
- if (chessBoard[row - 2][col + 1] == 0) {
- chessBoard[row - 2][col + 1] = i;
- row -= 2;
- col += 1;
- continue;
- }
- }
- if (row + 1 < N && col - 2 >= 0) {
- if (chessBoard[row + 1][col - 2] == 0) {
- chessBoard[row + 1][col - 2] = i;
- row += 1;
- col -= 2;
- continue;
- }
- }
- if (row - 1 >= 0 && col - 2 >= 0) {
- if (chessBoard[row - 1][col - 2] == 0) {
- chessBoard[row - 1][col - 2] = i;
- row -= 1;
- col -= 2;
- continue;
- }
- }
- if (row - 1 >= 0 && col + 2 < N) {
- if (chessBoard[row - 1][col + 2] == 0) {
- chessBoard[row - 1][col + 2] = i;
- row -= 1;
- col += 2;
- continue;
- }
- }
- if (row + 1 < N && col + 2 < N) {
- if (chessBoard[row + 1][col + 2] == 0) {
- chessBoard[row + 1][col + 2] = i;
- row += 1;
- col += 2;
- continue;
- }
- }
- if (row + 2 < N && col - 1 >= 0) {
- if (chessBoard[row + 2][col - 1] == 0) {
- chessBoard[row + 2][col - 1] = i;
- row += 2;
- col -= 1;
- continue;
- }
- }
- if (row + 2 < N && col + 1 < N) {
- if (chessBoard[row + 2][col + 1] == 0) {
- chessBoard[row + 2][col + 1] = i;
- row += 2;
- col += 1;
- continue;
- }
- }
- search :
- {
- for (int c = 0; c < N; c++) {
- for (int r = 0; r < N; r++) {
- if (chessBoard[r][c] == 0) {
- chessBoard[r][c] = i;
- right = 1;
- break search;
- }
- }
- }
- }
- }
- }
- for (int r = 0; r < N; r++) {
- for (int c = 0; c < N; c++) {
- System.out.print(chessBoard[r][c] + " ");
- }
- System.out.println();
- }
- return;
- }
- }
- }
Add Comment
Please, Sign In to add comment