0

This program working quite well. i wrote some exception ex N=1,2 and find others. I have a problem with a bord part when I give a number above 30 program waiting and freezing how can I solve that? I want to write for at least 255 or 150(max value). in there if N=30 or more program will stop when you want to run.

package com.company;
import java.util.Scanner;
public class NQueenProblem {
    Scanner scanner = new Scanner(System.in);

    final int N = Integer.valueOf(scanner.nextLine());

    void printSolution(int board[][]) {
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++)
                System.out.print(" " + board[i][j]
                        + " ");
            System.out.println();
        }
    }
safe condition is working correctly in big boards 

    boolean isSafe(int board[][], int row, int col) {
        int i, j;

        for (i = 0; i < col; i++)
            if (board[row][i] == 1)
                return false;

        for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
            if (board[i][j] == 1)
                return false;

        for (i = row, j = col; j >= 0 && i < N; i++, j--)
            if (board[i][j] == 1)
                return false;

        return true;
    }

    boolean solveNQUtil(int board[][], int col) {

        if (col >= N)
            return true;

        for (int i = 0; i < N; i++) {

            if (isSafe(board, i, col)) {

                board[i][col] = 1;


                if (solveNQUtil(board, col + 1) == true)
                    return true;

                board[i][col] = 0;
            }
        }

        return false;
    }

    boolean solveNQ() {
        int board[][]=new int[N][N];

        if (solveNQUtil(board, 0) == false) {
            System.out.print("Solution does not exist");
            return false;
        }

        printSolution(board);
        return true;
    }

    // driver program to test above function
    public static void main(String args[]) {
        NQueenProblem Queen = new NQueenProblem();
        Queen.solveNQ();
    }
}
DeadSilent
  • 35
  • 6
  • Where did you run this? – Turtle Nov 25 '21 at 08:42
  • I used Intellij IDE – DeadSilent Nov 25 '21 at 08:47
  • I cannot confirm the behavior in REPL. For N=29, it does take a few seconds and prints the answer. But for `30` it does not crash - it just takes a very long time (around a minute for me). I tested `31` and `50` as well but that took too long. https://replit.com/@pdormeier99/CandidIndelibleActivecell#Main.java – Der_Reparator Nov 25 '21 at 08:59
  • 1
    @DeadSilent Have a look at [this](https://stackoverflow.com/questions/21059422/time-complexity-of-n-queen-using-backtracking/21059499) – Turtle Nov 25 '21 at 09:01
  • 1
    @Turtle Yes, that's the answer. The type of algorithm @DeadSilent is using happens to become unbearably computationally inefficient at around `N=30`. – Der_Reparator Nov 25 '21 at 09:05

0 Answers0