• 51. N皇后


    class Solution {
    	int count;
    	List ls;
    	int n;
    	boolean bool[][];
    
    	public List<List<String>> solveNQueens(int n) {
    		count = 0;
    		ls = new LinkedList();
    		bool = new boolean[n][n];
    		this.n = n;
    		dfs(0);
    		return ls;
    	}
    
    	private void dfs(int x) {
    		if (x == n) {
    			ArrayList<String> path = new ArrayList<String>();
    		
    			for(int i = 0 ; i < n ; i++) {
    				StringBuffer stb = new StringBuffer("");
    				for(int j = 0 ; j < n ; j++) {
    				if(bool[i][j] == true )
    					stb.append("Q");
    				else stb.append(".");
    				}
    				path.add(stb.toString());
    			}
    			ls.add(path);
    			return;
    		}
    		for (int i = 0; i < n; i++) {
    			int temp = x;
    			int flag = 0;
    			while (temp >= 0) {
    				if((i+flag<n&&bool[temp][i+flag])||(i-flag>=0&&bool[temp][i-flag])||bool[temp][i])break;
    				temp--;
    				flag++;
    			}
    			if(temp==-1) {
    				bool[x][i] = true;
    				dfs(x+1);
    				bool[x][i] = false;
    			}
    		}
    	}
    }
    
  • 相关阅读:
    [BJOI2019]排兵布阵
    关于DP题的状态定义转换和各种优化这档事
    容斥原理学习笔记
    莫比乌斯反演学习笔记
    每日进度
    每日进度
    每日进度
    每日进度
    每日进度
    每日进度
  • 原文地址:https://www.cnblogs.com/cznczai/p/11400170.html
Copyright © 2020-2023  润新知