zoukankan      html  css  js  c++  java
  • 九皇后

    import org.junit.Test;
    //回溯法求解
    public class QueenFind {
    
    	public static final int N = 8;
    	public static int count = 0;
    
    	@Test
    	public void test() {
    		int[][] arr = new int[8][8];
    		for (int i = 0; i < N; i++) {
    			for (int j = 0; j < N; j++) {
    				arr[i][j] = 0;
    			}
    		}
    		findQueen(0, arr);
    		System.out.println("count" + count);
    
    	}
    
    	public void findQueen(int row, int[][] arr) {
    		if (row == N) {
    			count++;
    			System.out.println("count" + count);
    			return;
    		}
    		for (int i = 0; i < N; i++) {
    			for (int j = 0; j < N; j++) {
    				arr[row][j] = 0;
    			}
    			arr[row][i] = 1;
    			for (int k = 0; k < N; k++) {
    				System.out.print(arr[row][k] + " ");
    			}
    			System.out.println();
    			System.out.println(row);
    			if (isSafety(arr, row, i)) {
    				findQueen(row + 1, arr);
    			}
    		}
    	}
    
    	private boolean isSafety(int[][] chess, int row, int col) {
    		// 判断中上、左上、右上是否安全
    		int step = 1;
    		while (row - step >= 0) {
    			if (chess[row - step][col] == 1) // 中上
    				return false;
    			if (col - step >= 0 && chess[row - step][col - step] == 1) // 左上
    				return false;
    			if (col + step < N && chess[row - step][col + step] == 1) // 右上
    				return false;
    
    			step++;
    		}
    		return true;
    	}
    }

  • 相关阅读:
    LR 两种录制:html与url
    性能测试心得之一
    杂记
    基于 python 的接口测试框架
    POJ3579 Median
    洛谷P4035 [JSOI2008]球形空间产生器
    洛谷P2455 [SDOI2006]线性方程组
    POJ2393 Yogurt factory
    洛谷P3763 [TJOI2017]DNA
    洛谷P2234 [HNOI2002]营业额统计
  • 原文地址:https://www.cnblogs.com/wei1/p/9582107.html
Copyright © 2011-2022 走看看