cthrpfbc
2022-04-10
#算法# #闲聊# 有没有小伙伴用java 广度优先搜索bfs写过n皇后问题,我写了但是错了,debug一直不行。 4皇后的话可以得到正确答案,8皇后就输出0了,网上关于bfs的八皇后写法太少了,我是找到python后改成java的,但是没改对。 代码如下: package 人工智能作业; import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; public class n皇后bfs { static int count = 0; static class State { int x; //row int y; //col ArrayList<Integer> rowList ; ArrayList<Integer> colList ; ArrayList<Integer> rowColSumList ; ArrayList<Integer> rowColDifList ; public State(int x, int y, ArrayList<Integer> rowList, ArrayList<Integer> colList, ArrayList<Integer> rowColSumList, ArrayList<Integer> rowColDifList) { this.x = x; this.y = y; this.rowList = rowList; this.colList = colList; this.rowColSumList = rowColSumList; this.rowColDifList = rowColDifList; } } public static void bfs(int num) {//num个皇后 也就是共num行num列 Queue<State> queue = new LinkedList<>(); for (int i = 0; i < num; i ) { ArrayList<Integer> rList = new ArrayList<Integer>(); rList.add(0); ArrayList<Integer> cList = new ArrayList<Integer>(); cList.add(i); ArrayList<Integer> rcSumList = new ArrayList<Integer>(); rcSumList.add(i);//0 i ArrayList<Integer> rcDifList = new ArrayList<Integer>(); rcDifList.add(-i);//0-i queue.add(new State(0, i, rList, cList, rcSumList, rcDifList)); } while (queue.size() != 0) { State tempState = queue.poll(); if (tempState != null){ int row = tempState.x; // int temy = tempState.y; ArrayList<Integer> temrowList = tempState.rowList; ArrayList<Integer> temcolList = tempState.colList; ArrayList<Integer> temrcSumList = tempState.rowColSumList; ArrayList<Integer> temrcDifList = tempState.rowColDifList; if (row == num - 1) { count ; // System.out.println(queue); continue; } row ; for (int col = 0; col < num; col ) { if (!temrowList.contains(row) && !temcolList.contains(col) && !temrcSumList.contains(row col) && !temrcDifList.contains(row - col)) { temrowList.add(row); temcolList.add(col); temrcSumList.add(row col); temrcDifList.add(row - col); queue.offer(new State(row, col, temrowList, temcolList, temrcSumList, temrcDifList)); } } } } } public static void main(String[] args) { bfs(8); System.out.println(count); } }
0个评论
点击登录,快来和大家讨论吧~
表情
图片
暂无评论
下载 APP