Search code examples
javaalgorithmbacktracking

How can I make this backtracking stop without using System.exit(0)?


static void LasVegas(int []tablero, int f, int ultimaReina){


    HashSet<Integer> enterosUsados = new HashSet<Integer>();


    if (ultimaReina!=-1) enterosUsados.add(ultimaReina);
    if ((ultimaReina-1) >=0){enterosUsados.add(ultimaReina-1);}
    if ((ultimaReina+1 != tablero.length) && (ultimaReina!=-1)){enterosUsados.add(ultimaReina+1);}
  //  if(ultimaReina+1!=tablero.length){enterosUsados.add(ultimaReina+1);}

    Random random = new Random();
        int posReina;

        if (f==tablero.length){
            printBoard(tablero);
            stop=System.currentTimeMillis();
            System.out.println(stop-start);
            System.exit(0);
            return;
        }

        do {

            do{
            posReina= Math.abs(random.nextInt())%tablero.length;
            }
            while(enterosUsados.add(posReina)==false);


            tablero[f]=posReina;

            if (check(tablero, f)){
                LasVegas(tablero, f+1, posReina);
            }



    } while (enterosUsados.size()<tablero.length);

  }

public static void main(String[] args) {

       // testChiCuadrado(410,30);

        int [] tablero = new int[8];
        Arrays.fill(tablero, -1);

        start = System.currentTimeMillis();
        LasVegas(tablero, 0, -1);


    }

static boolean  check (int [] array, int f){

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

       if (array[i]==array[f]) return false;

       if( Math.abs(array[f]-array[i])== Math.abs(f-i)) return false;


       } return true;



   }


   static void printBoard(int [] tablero) {

       char [] linea = new char[tablero.length];
       Arrays.fill(linea, '*');
       for (int i=0;i<tablero.length;i++){

           linea[tablero[i]]='D';
           System.out.println(new String(linea));
           linea[tablero[i]]='*';

       }

   }

I'm using a Las Vegas algorithm to generate random queen positions on a board, I'd like to do timing of it via multiple runs but I'm using System.exit(0) to stop the backtracking when a solution is found, if I don't stop there my algorithm gives other solutions, which I don't want.

Here:

       if (f==tablero.length){
            printBoard(tablero);
            stop=System.currentTimeMillis();
            System.out.println(stop-start);
            System.exit(0);
            return;
        } 

How can I change that and make the algorithm stop without System.exit(0) so that I can call It multiple times within a loop?


Solution

  • Change the return type of LasVegas to boolean. Remove the call to System.exit() and change the immediately following return; statement to return true;. Change the recursive call to:

    if (LasVegas(tablero, f+1, posReina)) return true;