Labfans是一个针对大学生、工程师和科研工作者的技术社区。 论坛首页 | 联系我们(Contact Us)
MATLAB爱好者论坛-LabFans.com
返回   MATLAB爱好者论坛-LabFans.com > 其它 > 资料存档
资料存档 资料存档
回复
 
主题工具 显示模式
旧 2019-12-10, 20:41   #1
poster
高级会员
 
注册日期: 2019-11-21
帖子: 3,006
声望力: 66
poster 正向着好的方向发展
帖子 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
poster 当前离线   回复时引用此帖
回复


发帖规则
不可以发表新主题
不可以发表回复
不可以上传附件
不可以编辑自己的帖子

启用 BB 代码
论坛禁用 表情符号
论坛启用 [IMG] 代码
论坛启用 HTML 代码



所有时间均为北京时间。现在的时间是 05:14


Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.