Leetcode题解(7)L51/N-Queens

L51: N-Queens

  The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that

no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens’ placement, where ‘Q’ and ‘.’ both indicate a queen and an empty space respectively.

For example,

There exist two distinct solutions to the 4-queens puzzle:

[

  [“.Q..”, // Solution 1

  “…Q”,

  “Q…”,

  “..Q.”],

  [“..Q.”, // Solution 2

  “Q…”,

  “…Q”,

  “.Q..”]

]

解题思路:典型的回溯法,可用递归或非递归解决

class Solution {
public:
    bool isAttack(vector<int> queens, int k)
    {
        if(k == 0)
            return false;
        for (int i=0; i<k; i++)
        {
            if(queens[k] == queens[i] || abs(k-i) == abs(queens[k]-queens[i]))
                return true;
        }
        return false;
    }

    void showQueens(vector<int> queens, vector<vector<string> >& result){
        int n = queens.size();
        vector<string> vec(n, string(n,‘.‘));

        for(int i = 0; i < n; i++)
            vec[i][queens[i]] = ‘Q‘;

        result.push_back(vec);
    }

    vector<vector<string> > solveNQueens(int n) {
        vector<vector<string> > result;
        vector<int> queens(n,0);

        if(n == 1)
        {
            vector<string> vec(1, string(‘Q‘));
            result.push_back(vec);
            return result;
        }

        int i = 0;

        while(1)
        {
            while(i < n)
            {
                while(queens[i] == n)
                {
                    queens[i--] = 0;
                    if(i == -1)
                        return result;
                    queens[i]++;
                }
                if(isAttack(queens,i))
                    queens[i]++;
                else
                    i++;
            }
            showQueens(queens,result);

            queens[n-1] = 0;
            i = n-2;
            queens[i]++;
        }
    }
};
时间: 2024-10-23 12:25:16

Leetcode题解(7)L51/N-Queens的相关文章

(leetcode题解)Pascal&#39;s Triangle

Pascal's Triangle  Given numRows, generate the first numRows of Pascal's triangle. For example, given numRows = 5,Return [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] 题意实现一个杨辉三角. 这道题只要注意了边界条件应该很好实现出来,C++实现如下 vector<vector<int>> generate(int

[LeetCode]题解(python):031-Next Permutation

题目来源 https://leetcode.com/problems/next-permutation/ Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, it must rearrange it as the lowest possible

leetcode 题解:Search in Rotated Sorted Array II (旋转已排序数组查找2)

题目: Follow up for "Search in Rotated Sorted Array":What if duplicates are allowed? Would this affect the run-time complexity? How and why? Write a function to determine if a given target is in the array. 说明: 1)和1比只是有重复的数字,整体仍采用二分查找 2)方法二 : 实现:  

[LeetCode 题解]: Binary Tree Preorder Traversal

Given a binary tree, return the preorder traversal of its nodes' values. For example:Given binary tree {1,#,2,3}, 1 2 / 3 return [1,2,3]. Note: Recursive solution is trivial, could you do it iteratively? 题意 先序遍历二叉树,递归的思路是普通的,能否用迭代呢? 非递归思路:<借助stack>

LeetCode题解

Reverse Words in a String 考虑几个特殊的情况1.若字符窜s="  "2.字符窜s=“a  b  d     e”3.字符窜s=“ a” class Solution { public: void reverseWords(string &s) { int i; int cas=0; string st[100]; s+=' '; for(i=0;i<s.size();i++) { if(i==0 && s[0]==' ') con

leetcode题解:Search in Rotated Sorted Array(旋转排序数组查找)

题目: Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). You are given a target value to search. If found in the array return its index, otherwise return -1. You may assume no du

[LeetCode 题解]: Reverse Nodes in K-Groups

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is. You may not alter the values in the nodes, only nod

[LeetCode 题解]: Linked List Cycle II

Given a linked list, return the node where the cycle begins. If there is no cycle, return null. Follow up:Can you solve it without using extra space? 题意: 给定一个链表,找到环起始的位置.如果环不存在,返回NULL. 分析: (1)首先要判断该链表是否有环.如果没有环,那么返回NULL. (2)其次,当已知环存在后,寻找环起始的位置. 思路: (

[LeetCode 题解]:Candy

There are N children standing in a line. Each child is assigned a rating value. You are giving candies to these children subjected to the following requirements: Each child must have at least one candy. Children with a higher rating get more candies

[LeetCode: 题解] Combination Sum

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The same repeated number may be chosen from C unlimited number of times. Note: All numbers (including target) will