Matlab N-Queen Problem

Posted by Kay on Stack Overflow See other posts from Stack Overflow or by Kay
Published on 2010-06-10T21:04:28Z Indexed on 2010/06/10 21:33 UTC
Read the original article Hit count: 424

Filed under:
|

main.m

counter = 1;
n = 8;
board = zeros(1,n);
back(0, board);
disp(counter);

sol.m

function value = sol(board)

for ( i = 1:(length(board)))
   for ( j = (i+1): (length(board)-1))
       if (board(i) == board(j))
          value = 0;
          return;
       end
       if ((board(i) - board(j)) == (i-j))
          value = 0;
          return;
       end
       if ((board(i) - board(j)) == (j-i))
          value = 0;
          return;
       end
   end
end
value = 1;
return;

back.m

function back(depth, board)

disp(board);

if ( (depth == length(board)) && (sol2(board) == 1))
    counter = counter + 1;
end

if ( depth < length(board))
   for ( i = 0:length(board))
       board(1,depth+1) = i;
       depth = depth + 1;
       solv2(depth, board);
   end
end

I'm attempting to find the maximum number of ways n-queen can be placed on an n-by-n board such that those queens aren't attacking eachother. I cannot figure out the problem with the above matlab code, i doubt it's a problem with my logic since i've tested out this logic in java and it seems to work perfectly well there. The code compiles but the issue is that the results it produces are erroneous.

Java Code which works:

               public static int counter=0;

                public static boolean isSolution(final int[] board){
                    for (int i = 0; i < board.length; i++) {
                        for (int j = i + 1; j < board.length; j++) {
                            if (board[i] == board[j]) return false;    
                            if (board[i]-board[j] == i-j) return false; 
                            if (board[i]-board[j] == j-i) return false; 
                        }
                    }
                    return true;
                }

                public static void solve(int depth, int[] board){

                    if (depth == board.length && isSolution(board)) {
                        counter++;
                 }
               if (depth < board.length) {  // try all positions of the next row

                for (int i = 0; i < board.length; i++) {
                            board[depth] = i;
                            solve(depth + 1, board);
                        }
                    }
                }


                    public static void main(String[] args){
                        int n = 8;
                        solve(0, new int[n]);
                    System.out.println(counter);
                    }

© Stack Overflow or respective owner

Related posts about matlab

Related posts about n-queens