第一次实验,八皇后问题
2014-06-12 09:56
267 查看
public class EightQueen { private int index = 1; private final static int SCALE = 8; private int[] answer = new int[SCALE]; private void initArray() { for (int i = 0; i < answer.length; i++) { answer[i] = -1; } } private boolean canStay(int row, int col) { for (int i = 0; i < row; i++) { if (answer[i] == col || Math.abs(row - i) == Math.abs(col - answer[i])) { return false; } } return true; } private void calculate() { for (int row = 0; row < SCALE; row++) { if (answer[row] == -1) { answer[row] = 0; } for (int col = answer[row]; col <= SCALE; col++) { if (col == SCALE) { answer[row] = -1; row--; if (row < 0) { return; } col = answer[row]; continue; } if (canStay(row, col)) { answer[row] = col; if (row == SCALE - 1) { showmsg(); continue; } break; } } } } private void showmsg() { if (index<4) { System.out.println(" - 第" + index + "种方案 -"); for (int i = 0; i < answer.length; i++) { for (int j = 0; j < SCALE; j++) { if (answer[i] == j) { System.out.print("Q "); } else { System.out.print("X "); } } System.out.println(""); } System.out.println("\n"); index++; } } public EightQueen() { initArray(); calculate(); } public static void main(String[] args) { System.out.println("列举"+SCALE+"皇后问题的前 3 种方案!"); System.out.println(); EightQueen eightQueen = new EightQueen(); } }
[/code]
相关文章推荐
- 第一次实验——八皇后问题
- 第一次实验——八皇后问题
- C++第一次实验—2
- 第一次上机实验-2
- 软件测试第一次实验/2016/3/18
- 第一次实验--NPC问题(回溯算法、聚类分析)
- 20145317彭垚 《Java程序设计》第一次实验实验报告
- 第一次实验:项目3两点距离
- C++第一次实验-标准体重的判断
- 《数据结构》第一次实验:VC编程环境灵活应用
- 第一次实验课课堂笔记
- 安卓第一次实验解析
- 数据压缩第一次实验报告(rgb与yuv的转换)
- 软件工程第一次实验
- 20155339《java程序设计》第一次实验报告
- SC的第一次实验
- 第一次实验
- C++第一次上机实验-2
- 第一次实验作业报告
- C++补第一次实验