当前位置:   article > 正文

【数据结构与算法】回溯法解决N皇后问题,java代码实现_java实现n皇后问题(回溯法)

java实现n皇后问题(回溯法)

N皇后问题

问题描述

在8×8格的国际象棋上摆放八个皇后,使其不能互相攻击,即任意两个皇后都不能处于同一行、同一列或同一斜线上,问有多少种摆法,这称为八皇后问题
延伸一下,便为N皇后问题。

核心思想

解决N皇后问题有两个关键点。一是如何进行放置棋子,二是如何验证棋子是否符合要求。

因此,我们利用回溯法建立函数。

 private static void NQueen(LinkedList<Location> list, int x, int y) {   

        if(list.size() == SIZE){  //当list元素个数为SIZE时,表示SIZE个皇后都摆放完毕,打印后即可退出函数。
            printLocation(list);  //打印皇后摆放方式
            return ;
        }

        for(int i = x ; i < SIZE ; i++){
            Location loc = new Location(i, y);
            if(isLegalLoc(list, loc)){
                list.offer(loc);  //将第y列的皇后摆放好
                NQueen(list, 0, y+1);  //开始摆放y+1列的皇后,同样从第0列开始摆放
                list.pollLast();  //每次摆放完一个皇后后,都要将其撤回,再试探其它的摆法。
            }                   
        }           
    }

	
	/**
     * 判断位置为loc的皇后是否合法
     */
    private static boolean isLegalLoc(LinkedList<Location> list, Location loc) {
        for(Location each : list){
            if(loc.x == each.x || loc.y == each.y)  //判断是否在同一行或同一列
                return false;
            else if (Math.abs(loc.x - each.x) == Math.abs(loc.y - each.y))  //判断是否在同斜线上
                return false;
        }
        return true;
    }

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

这里对list.offer()进行补充。

  • offer 属于 offer in interface Deque,add 属于 add in interface Collection。
  • 当队列为空时候,使用add方法会报错,而offer方法会返回false。
  • 作为List使用时,一般采用add / get方法来 压入/获取对象。
  • 作为Queue使用时,才会采用 offer/poll/take等方法。

完整代码实现如下

import java.util.LinkedList;
import java.util.Scanner;

public class QueenN {

	private static int SIZE = 0;//皇后的个数
	private static int count = 0;//记录摆放的方式数
	public static void main(String[] args) {

		Scanner input = new Scanner(System.in);
		System.out.println("请输入你要解决几个皇后的问题");
		SIZE = input.nextInt();
		input.close();
		 LinkedList<Location> list = new LinkedList<Location>();
	     NQueen(list, 0, 0);  //从棋盘的第0行第0列开始
	     System.out.println(SIZE + "皇后共有 " + count + "种摆放方式");

	}
	static class Location{
		int x;//对应棋盘的行
		int y;//对应棋盘的列
		
		Location(int x,int y){
			this.x = x;
			this.y = y;
		}
		
		public String toString() {
			return "(" + x + "," + y + ")";
		}
	}
	
	/**
     * 主要函数,用回溯法。
     */
    private static void NQueen(LinkedList<Location> list, int x, int y) {   

        if(list.size() == SIZE){  //当list元素个数为SIZE时,表示SIZE个皇后都摆放完毕,打印后即可退出函数。
            printLocation(list);  //打印皇后摆放方式
            return ;
        }

        for(int i = x ; i < SIZE ; i++){
            Location loc = new Location(i, y);
            if(isLegalLoc(list, loc)){
                list.offer(loc);  //将第y列的皇后摆放好
                NQueen(list, 0, y+1);  //开始摆放y+1列的皇后,同样从第0列开始摆放
                list.pollLast();  //每次摆放完一个皇后后,都要将其撤回,再试探其它的摆法。
            }                   
        }           
    }

	
	/**
     * 判断位置为loc的皇后是否合法
     */
    private static boolean isLegalLoc(LinkedList<Location> list, Location loc) {
        for(Location each : list){
            if(loc.x == each.x || loc.y == each.y)  //判断是否在同一行或同一列
                return false;
            else if (Math.abs(loc.x - each.x) == Math.abs(loc.y - each.y))  //判断是否在同斜线上
                return false;
        }
        return true;
    }

    /**
     * 打印皇后摆放方式
     * @param list
     */
    private static void printLocation(LinkedList<Location> list) {
    	String[][] show = new String[SIZE][SIZE]; 
    	for(int i = 0;i<SIZE;i++) {
    		for(int j = 0;j<SIZE;j++) {
    			show[i][j] = "0";
    		}
    	}
    	for(Location each : list){
            System.out.print(each.toString() + "\t");
            show[each.x][each.y] = "1";
        }
        System.out.println();
        
        for(int i =0;i<SIZE;i++) {
        	for(int j=0;j<SIZE;j++) {
        		System.out.print(show[i][j] + " ");
        	}
        	System.out.println();
        }
        System.out.println();

        count ++;
    }

}


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/633317
推荐阅读
相关标签
  

闽ICP备14008679号