Matlab N-Queen问题
主目录
counter = 1; n = 8; board = zeros(1,n); back(0, board); disp(counter); 溶胶
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)) == (ij)) value = 0; return; end if ((board(i) - board(j)) == (ji)) value = 0; return; end end end value = 1; return; 后退
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 我试图找到最多的方法,可以将n-queen放置在n-n-n板上,以使这些皇后不会互相攻击。我无法弄清楚上面的matlab代码存在的问题,我怀疑这是我的逻辑问题,因为我已经在Java中测试了该逻辑,并且看起来在那里工作得很好。代码可以编译,但是问题在于它产生的结果是错误的。
适用的Java代码:
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] == ij) return false; if (board[i]-board[j] == ji) 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); }
回答:
工作的代码:
function queen clc; counter = 0; n = 8; board = zeros(1,n); [board,counter] = back(1, board,counter); fprintf('Solution count: %d\n',counter); %% function value = isSolution(board) for i = 1:length(board) for j = (i+1): length(board) if abs(board(i) - board(j)) == abs(ij) value = false; return; end end end value = true; %% function [board,counter] = back(depth, board,counter) if (depth == length(board)+1) && isSolution(board) counter = counter + 1; disp(board); end if ( depth
|