码迷,mamicode.com
首页 > 其他好文 > 详细

八皇后问题(回溯)

时间:2014-12-06 06:40:17      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:八皇后 java

public class Queen {
    
    int QUEEN_COUNT = 8;    //随便你定义几个皇后了,你可以循环产生a个到b个皇后的解
    static final int EMPTY = 0;  //如果count[x][y] == EMPTY ,则可以放置皇后;反之,其正上方或斜上方必己放置皇后
    int[][] count = new int[QUEEN_COUNT][QUEEN_COUNT]; //
    int[] QueenIndex = new int[QUEEN_COUNT]; //第index行的皇后放置位置是QueenIndex [index]
    int resultCount = 0; //记录皇后放置方法的数量
    
    public void putQueenIndex(int index) {
        int row = index;
        for (int col = 0; col < QUEEN_COUNT; col++) {
            if (count[row][col] == EMPTY) { //该位置可以放置皇后
                for (int iRow = row+ 1; iRow < QUEEN_COUNT; iRow++) { //增加该位置的正下面/斜下面的count,使之不为0
                    count[iRow][col]++;
                    if ((col - iRow + row) >= 0) {
                        count[iRow][col - iRow + row]++;
                    }
                    if ((col + iRow - row) < QUEEN_COUNT) {
                        count[iRow][col + iRow - row]++;
                    }
                }
                QueenIndex[row] = col;
                if (row == QUEEN_COUNT - 1) { //第QUEEN_COUNT个皇后己放置好,打印出这种皇后布局
                    print(++resultCount);
                } else { //继续放置下一行的皇后
                    putQueenIndex(row + 1);
                }
                for (int iRow = row+ 1; iRow < QUEEN_COUNT; iRow++) { //回溯,在此行的皇后不放此列col ,恢复该位置的正下面/斜下面的count
                    count[iRow][col]--;
                    if ((col - iRow + row) >= 0) {
                        count[iRow][col - iRow + row]--;
                    }
                    if ((col + iRow - row) < QUEEN_COUNT) {
                        count[iRow][col + iRow - row]--;
                    }
                }
            }
        }
        if (row == 0) { 
            System.out.println(QUEEN_COUNT + "皇后共有 " + resultCount + " 个解");
        }
    }
    
    public void print(int n) { //打印皇后布局
        System.out.println(QUEEN_COUNT + "皇后的第 " + n + " 个解:");
        for (int i = 0; i < QUEEN_COUNT; i++) {
            for (int j = 0; j < QUEEN_COUNT; j++) {
                System.out.print(QueenIndex[i] == j ? " * " : " - ");
            }
            System.out.println();
        }
        System.out.println();
    }
    
    public static void main(String[] args) {
        new Queen().putQueenIndex(0);
    }
}

代码运行结果:

bubuko.com,布布扣bubuko.com,布布扣





本文出自 “闲庭信步、” 博客,请务必保留此出处http://macxiao.blog.51cto.com/9606147/1586804

八皇后问题(回溯)

标签:八皇后 java

原文地址:http://macxiao.blog.51cto.com/9606147/1586804

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!