• 九皇后


    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;
    	}
    }

  • 相关阅读:
    webpack 关于跨域的配置
    如何使用css变量
    样式重置
    vue+element_ui上传文件,并传递额外参数(自动上传)
    LeetCode-46-全排列
    LeetCode-39-组合总数
    LeetCode-33-搜索旋转排序数组
    LeetCode-207-课程表
    LeetCode-15-三数之和
    LeetCode-盛最多水的容器
  • 原文地址:https://www.cnblogs.com/wei1/p/9582107.html
Copyright © 2020-2023  润新知