中的所有pg电子试玩链接的解决方案

原文:

n 皇后是把 n 个象棋皇后放在 n×n 个棋盘上,使得没有两个皇后互相攻击的问题。例如,以下是 4 皇后问题的pg电子试玩链接的解决方案。 n 皇后就是把 n 个象棋皇后放在 n×n 的棋盘上,这样就不会有两个皇后互相攻击的问题。例如,以下是 4 皇后问题的两种pg电子试玩链接的解决方案。

在帖子中,我们讨论了一种只打印一个可能pg电子试玩链接的解决方案的方法,所以现在在这篇帖子中,任务是打印 n-queen problem 中的所有pg电子试玩链接的解决方案。每个解包含 n 皇后位置的不同板配置,其中解是[1,2,3]的排列..n]按递增顺序,此处第和第位的数字表示第列的第皇后位于该数字所在的行中。对于上述示例,pg电子试玩链接的解决方案写成[[2 4 1 3 ] [3 1 4 2 ]]。这里讨论的pg电子试玩链接的解决方案是同一方法的扩展。

回溯算法

想法是将皇后一个接一个地放在不同的列中,从最左边的列开始。当我们在一列中放置一个皇后时,我们检查与已经放置的皇后的冲突。在当前列中,如果我们找到没有冲突的行,我们将该行和列标记为pg电子试玩链接的解决方案的一部分。如果由于冲突我们没有找到这样的行,那么我们回溯并返回 false。

1) start in the leftmost column
2) if all queens are placed
    return true
3) try all rows in the current column.  do following
   for every tried row.
    a) if the queen can be placed safely in this row
       then mark this [row, column] as part of the 
       solution and recursively check if placing  
       queen here leads to a solution.
    b) if placing queen in [row, column] leads to a
       solution then return true.
    c) if placing queen doesn't lead to a solution 
       then unmark this [row, column] (backtrack) 
       and go to step (a) to try other rows.
3) if all rows have been tried and nothing worked, 
   return false to trigger backtracking.

一个修改是我们可以在 o(1)时间内找到我们之前放置的皇后是在一列还是在左对角线还是在右对角线。我们可以观察到

1)对于特定左对角线中的所有单元,它们的行 列=常数。

2)对于特定右对角线中的所有单元格,它们的行–col n–1 =常数。

假设 n = 5,那么我们总共有 2n-1 条左右对角线

假设我们在(2,0)处放置了一个皇后

(2,0)的左对角线值= 2。现在我们不能在(1,1)和(0,2)放置另一个皇后,因为这两个皇后的左对角线值与(2,0)相同。右对角线也可以看到类似的情况。

c

/* c/c   program to solve n queen problem using
backtracking */
#include 
using namespace std;
vector > result;
/* a utility function to check if a queen can
be placed on board[row][col]. note that this
function is called when "col" queens are
already placed in columns from 0 to col -1.
so we need to check only left side for
attacking queens */
bool issafe(vector > board,
            int row, int col)
{
    int i, j;
    int n = board.size();
    /* check this row on left side */
    for (i = 0; i < col; i  )
        if (board[row][i])
            return false;
    /* check upper diagonal on left side */
    for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
        if (board[i][j])
            return false;
    /* check lower diagonal on left side */
    for (i = row, j = col; j >= 0 && i < n; i  , j--)
        if (board[i][j])
            return false;
    return true;
}
/* a recursive utility function to solve n
queen problem */
bool solvenqutil(vector >& board, int col)
{
    /* base case: if all queens are placed
    then return true */
    int n = board.size();
    if (col == n) {
        vector v;
        for (int i = 0; i < n; i  ) {
            for (int j = 0; j < n; j  ) {
                if (board[i][j] == 1)
                    v.push_back(j   1);
            }
        }
        result.push_back(v);
        return true;
    }
    /* consider this column and try placing
    this queen in all rows one by one */
    bool res = false;
    for (int i = 0; i < n; i  ) {
        /* check if queen can be placed on
        board[i][col] */
        if (issafe(board, i, col)) {
            /* place this queen in board[i][col] */
            board[i][col] = 1;
            // make result true if any placement
            // is possible
            res = solvenqutil(board, col   1) || res;
            /* if placing queen in board[i][col]
            doesn't lead to a solution, then
            remove queen from board[i][col] */
            board[i][col] = 0; // backtrack
        }
    }
    /* if queen can not be place in any row in
        this column col then return false */
    return res;
}
/* this function solves the n queen problem using
backtracking. it mainly uses solvenqutil() to
solve the problem. it returns false if queens
cannot be placed, otherwise return true and
prints placement of queens in the form of 1s.
please note that there may be more than one
solutions, this function prints one of the
feasible solutions.*/
vector > nqueen(int n)
{
    result.clear();
    vector > board(n, vector(n, 0));
    if (solvenqutil(board, 0) == false) {
        return {};
    }
    sort(result.begin(), result.end());
    return result;
}
// driver code
int main()
{
    int n = 4;
    vector > v = nqueen(n);
    for (auto ar : v) {
        cout << "[";
        for (auto it : ar)
            cout << it << " ";
        cout << "]";
    }
    return 0;
}

java 语言(一种计算机语言,尤用于创建网站)

/* java program to solve n queen
problem using backtracking */
import java.util.*;
class gfg {
  /* this function solves the n queen problem using
    backtracking. it mainly uses solvenqutil() to
    solve the problem.
    */
    static list> nqueen(int n) {
       // cols[i] = true if there is a queen previously placed at ith column
        cols = new boolean[n];
        // leftdiagonal[i] = true if there is a queen previously placed at
          // i = (row   col )th left diagonal
        leftdiagonal = new boolean[2*n];
          // rightdiagonal[i] = true if there is a queen previously placed at
          // i = (row - col   n - 1)th rightdiagonal diagonal
        rightdiagonal = new boolean[2*n];
        result  = new arraylist<>();
        list temp = new arraylist<>();
        for(int i=0;i> result,int n,int row,list comb){
        if(row==n){
          // if row==n it means we have successfully placed all n queens.
          // hence add current arrangement to our answer
          // comb represent current combination
            result.add(new arraylist<>(comb));
            return;
        }
        for(int col = 0;col > result
        = new arraylist >();
   static boolean[] cols,leftdiagonal,rightdiagonal;
    // driver code
    public static void main(string[] args)
    {
        int n = 4;
        list > res = nqueen(n);
        system.out.println(res);
    }
}

python 3

''' python3 program to solve n queen problem using
backtracking '''
result = []
# a utility function to print solution
''' a utility function to check if a queen can
be placed on board[row][col]. note that this
function is called when "col" queens are
already placed in columns from 0 to col -1.
so we need to check only left side for
attacking queens '''
def issafe(board, row, col):
    # check this row on left side
    for i in range(col):
        if (board[row][i]):
            return false
    # check upper diagonal on left side
    i = row
    j = col
    while i >= 0 and j >= 0:
        if(board[i][j]):
            return false
        i -= 1
        j -= 1
    # check lower diagonal on left side
    i = row
    j = col
    while j >= 0 and i < 4:
        if(board[i][j]):
            return false
        i = i   1
        j = j - 1
    return true
''' a recursive utility function to solve n
queen problem '''
def solvenqutil(board, col):
    ''' base case: if all queens are placed
    then return true '''
    if (col == 4):
        v = []
        for i in board:
          for j in range(len(i)):
            if i[j] == 1:
              v.append(j 1)
        result.append(v)
        return true
    ''' consider this column and try placing
    this queen in all rows one by one '''
    res = false
    for i in range(4):
        ''' check if queen can be placed on
        board[i][col] '''
        if (issafe(board, i, col)):
            # place this queen in board[i][col]
            board[i][col] = 1
            # make result true if any placement
            # is possible
            res = solvenqutil(board, col   1) or res
            ''' if placing queen in board[i][col]
            doesn't lead to a solution, then
            remove queen from board[i][col] '''
            board[i][col] = 0  # backtrack
    ''' if queen can not be place in any row in
        this column col then return false '''
    return res
''' this function solves the n queen problem using
backtracking. it mainly uses solvenqutil() to
solve the problem. it returns false if queens
cannot be placed, otherwise return true and
prints placement of queens in the form of 1s.
please note that there may be more than one
solutions, this function prints one of the
feasible solutions.'''
def solvenq(n):
    result.clear()
    board = [[0 for j in range(n)]
             for i in range(n)]
    solvenqutil(board, 0)
    result.sort()
    return result
# driver code
n = 4
res = solvenq(n)
print(res)
# this code is contributed by yatingupta

c

/* c# program to solve n queen
problem using backtracking */
using system;
using system.collections;
using system.collections.generic;
class gfg {
    static list > result = new list >();
    /* a utility function to check if a queen can
    be placed on board[row,col]. note that this
    function is called when "col" queens are
    already placed in columns from 0 to col -1.
    so we need to check only left side for
    attacking queens */
    static bool issafe(int[, ] board, int row, int col,
                       int n)
    {
        int i, j;
        /* check this row on left side */
        for (i = 0; i < col; i  )
            if (board[row, i] == 1)
                return false;
        /* check upper diagonal on left side */
        for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
            if (board[i, j] == 1)
                return false;
        /* check lower diagonal on left side */
        for (i = row, j = col; j >= 0 && i < n; i  , j--)
            if (board[i, j] == 1)
                return false;
        return true;
    }
    /* a recursive utility function
    to solve n queen problem */
    static bool solvenqutil(int[, ] board, int col, int n)
    {
        /* base case: if all queens are placed
        then return true */
        if (col == n) {
            list v = new list();
            for (int i = 0; i < n; i  )
                for (int j = 0; j < n; j  ) {
                    if (board[i, j] == 1)
                        v.add(j   1);
                }
            result.add(v);
            return true;
        }
        /* consider this column and try placing
        this queen in all rows one by one */
        bool res = false;
        for (int i = 0; i < n; i  ) {
            /* check if queen can be placed on
            board[i,col] */
            if (issafe(board, i, col, n)) {
                /* place this queen in board[i,col] */
                board[i, col] = 1;
                // make result true if any placement
                // is possible
                res = solvenqutil(board, col   1, n) || res;
                /* if placing queen in board[i,col]
                doesn't lead to a solution, then
                remove queen from board[i,col] */
                board[i, col] = 0; // backtrack
            }
        }
        /* if queen can not be place in any row in
            this column col then return false */
        return res;
    }
    /* this function solves the n queen problem using
    backtracking. it mainly uses solvenqutil() to
    solve the problem. it returns false if queens
    cannot be placed, otherwise return true and
    prints placement of queens in the form of 1s.
    please note that there may be more than one
    solutions, this function prints one of the
    feasible solutions.*/
    static list > solvenq(int n)
    {
        result.clear();
        int[, ] board = new int[n, n];
        solvenqutil(board, 0, n);
        return result;
    }
    // driver code
    public static void main()
    {
        int n = 4;
        list > res = solvenq(n);
        for (int i = 0; i < res.count; i  ) {
            console.write("[");
            for (int j = 0; j < res[i].count; j  ) {
                console.write(res[i][j]  " ");
            }
            console.write("]");
        }
    }
}
/* this code contributed by princiraj1992 */

output

[2 4 1 3 ][3 1 4 2 ]

使用位屏蔽的高效回溯方法

算法: 每行每列总是只有一个皇后,所以回溯的思路是从每行最左边一列开始放置皇后,找到一列可以放置皇后的位置,而不会与之前放置的皇后发生冲突。它从第一行重复到最后一行。放置皇后时,它会被跟踪,就好像它没有与前几行中放置的皇后发生碰撞(行方向、列方向和对角线方向)。一旦发现皇后不能被放置在一行中的特定列索引处,算法回溯并改变放置在前一行的皇后的位置,然后向前移动以将皇后放置在下一行。

  1. 从三位向量开始,该向量用于在每次迭代中逐行、逐列和对角跟踪皇后位置的安全位置。
  2. 三位向量将包含如下信息:
    • rowmask: 设置该位向量的位索引(i)将指示,皇后不能放置在下一行的第 i 列。
    • ldmask: 设置该位向量的位索引(i)将指示,皇后不能被放置在下一行的第 i 列。它表示下一行的不安全列索引位于前一行皇后的左对角线下。
    • rdmask: 设置该位向量的位索引(i)将指示,皇后不能放置在下一行的第 i 列。它表示下一行的不安全列索引落在前一行皇后的右对角线上。
  3. 有一个二维(nxn)矩阵(板),它将在开始的所有索引处有“”字符,并由“q”逐行填充。一旦所有行都被“q”填充,当前的pg电子试玩链接的解决方案将被推入结果列表。

下面是上述方法的实现:

c

// cpp program for above approach
#include 
using namespace std;
vector > result;
// program to solve n queens problem
void solveboard(vector >& board, int row,
                int rowmask, int ldmask, int rdmask,
                int& ways)
{
    int n = board.size();
    // all_rows_filled is a bit mask having all n bits set
    int all_rows_filled = (1 << n) - 1;
    // if rowmask will have all bits set, means queen has
    // been placed successfully in all rows and board is
    // displayed
    if (rowmask == all_rows_filled) {
        vector v;
        for (int i = 0; i < board.size(); i  ) {
            for (int j = 0; j < board.size(); j  ) {
                if (board[i][j] == 'q')
                    v.push_back(j   1);
            }
        }
        result.push_back(v);
        return;
    }
    // we extract a bit mask(safe) by rowmask,
    // ldmask and rdmask. all set bits of 'safe'
    // indicates the safe column index for queen
    // placement of this iteration for row index(row).
    int safe
        = all_rows_filled & (~(rowmask | ldmask | rdmask));
    while (safe) {
        // extracts the right-most set bit
        // (safe column index) where queen
        // can be placed for this row
        int p = safe & (-safe);
        int col = (int)log2(p);
        board[row][col] = 'q';
        // this is very important:
        // we need to update rowmask, ldmask and rdmask
        // for next row as safe index for queen placement
        // will be decided by these three bit masks.
        // we have all three rowmask, ldmask and
        // rdmask as 0 in beginning. suppose, we are placing
        // queen at 1st column index at 0th row. rowmask,
        // ldmask and rdmask will change for next row as
        // below:
        // rowmask's 1st bit will be set by or operation
        // rowmask = 00000000000000000000000000000010
        // ldmask will change by setting 1st
        // bit by or operation  and left shifting
        // by 1 as it has to block the next column
        // of next row because that will fall on left
        // diagonal. ldmask =
        // 00000000000000000000000000000100
        // rdmask will change by setting 1st bit
        // by or operation and right shifting by 1
        // as it has to block the previous column
        // of next row because that will fall on right
        // diagonal. rdmask =
        // 00000000000000000000000000000001
        // these bit masks will keep updated in each
        // iteration for next row
        solveboard(board, row   1, rowmask | p,
                   (ldmask | p) << 1, (rdmask | p) >> 1,
                   ways);
        // reset right-most set bit to 0 so,
        // next iteration will continue by placing the queen
        // at another safe column index of this row
        safe = safe & (safe - 1);
        // backtracking, replace 'q' by ' '
        board[row][col] = ' ';
    }
    return;
}
// driver code
int main()
{
    // board size
    int n = 4;
    int ways = 0;
    vector > board;
    for (int i = 0; i < n; i  ) {
        vector tmp;
        for (int j = 0; j < n; j  ) {
            tmp.push_back(' ');
        }
        board.push_back(tmp);
    }
    int rowmask = 0, ldmask = 0, rdmask = 0;
    int row = 0;
    // function call
    result.clear();
    solveboard(board, row, rowmask, ldmask, rdmask, ways);
    sort(result.begin(),result.end());
    for (auto ar : result) {
        cout << "[";
        for (auto it : ar)
            cout << it << " ";
        cout << "]";
    }
    return 0;
}
// this code is contributed by nikhil vinay

java 语言(一种计算机语言,尤用于创建网站)

// java program for above approach
import java.util.*;
public class nqueensolution {
    static list > result
        = new arraylist >();
    // program to solve n-queens problem
    public void solveboard(char[][] board, int row,
                           int rowmask, int ldmask,
                           int rdmask)
    {
        int n = board.length;
        // all_rows_filled is a bit mask
        // having all n bits set
        int all_rows_filled = (1 << n) - 1;
        // if rowmask will have all bits set,
        // means queen has been placed successfully
        // in all rows and board is displayed
        if (rowmask == all_rows_filled) {
            list v = new arraylist<>();
            for (int i = 0; i < n; i  ) {
                for (int j = 0; j < n; j  ) {
                    if (board[i][j] == 'q')
                        v.add(j   1);
                }
            }
            result.add(v);
            return;
        }
        // we extract a bit mask(safe) by rowmask,
        // ldmask and rdmask. all set bits of 'safe'
        // indicates the safe column index for queen
        // placement of this iteration for row index(row).
        int safe = all_rows_filled
                   & (~(rowmask | ldmask | rdmask));
        while (safe > 0) {
            // extracts the right-most set bit
            // (safe column index) where queen
            // can be placed for this row
            int p = safe & (-safe);
            int col = (int)(math.log(p) / math.log(2));
            board[row][col] = 'q';
            // this is very important:
            // we need to update rowmask, ldmask and rdmask
            // for next row as safe index for queen
            // placement will be decided by these three bit
            // masks.
            // we have all three rowmask, ldmask and
            // rdmask as 0 in beginning. suppose, we are
            // placing queen at 1st column index at 0th row.
            // rowmask, ldmask and rdmask will change for
            // next row as below:
            // rowmask's 1st bit will be set by or operation
            // rowmask = 00000000000000000000000000000010
            // ldmask will change by setting 1st
            // bit by or operation  and left shifting
            // by 1 as it has to block the next column
            // of next row because that will fall on left
            // diagonal. ldmask =
            // 00000000000000000000000000000100
            // rdmask will change by setting 1st bit
            // by or operation and right shifting by 1
            // as it has to block the previous column
            // of next row because that will fall on right
            // diagonal. rdmask =
            // 00000000000000000000000000000001
            // these bit masks will keep updated in each
            // iteration for next row
            solveboard(board, row   1, rowmask | p,
                       (ldmask | p) << 1,
                       (rdmask | p) >> 1);
            // reset right-most set bit to 0 so,
            // next iteration will continue by placing the
            // queen at another safe column index of this
            // row
            safe = safe & (safe - 1);
            // backtracking, replace 'q' by ' '
            board[row][col] = ' ';
        }
    }
    // program to print board
    public void printboard(char[][] board)
    {
        for (int i = 0; i < board.length; i  ) {
            system.out.print("|");
            for (int j = 0; j < board[i].length; j  ) {
                system.out.print(board[i][j]   "|");
            }
            system.out.println();
        }
    }
    // driver code
    public static void main(string args[])
    {
        // board size
        int n = 4;
        char board[][] = new char[n][n];
        for (int i = 0; i < n; i  ) {
            for (int j = 0; j < n; j  ) {
                board[i][j] = ' ';
            }
        }
        int rowmask = 0, ldmask = 0, rdmask = 0;
        int row = 0;
        nqueensolution solution = new nqueensolution();
        // function call
        result.clear();
        solution.solveboard(board, row, rowmask, ldmask,
                            rdmask);
        system.out.println(result);
    }
}
// this code is contributed by nikhil vinay

python 3

# python program for above approach
import math
result = []
# program to solve n-queens problem
def solveboard(board, row, rowmask,
               ldmask, rdmask):
    n = len(board)
    # all_rows_filled is a bit mask
    # having all n bits set
    all_rows_filled = (1 << n) - 1
    # if rowmask will have all bits set, means
    # queen has been placed successfully
    # in all rows and board is displayed
    if (rowmask == all_rows_filled):
        v = []
        for i in board:
            for j in range(len(i)):
                if i[j] == 'q':
                    v.append(j 1)
        result.append(v)
    # we extract a bit mask(safe) by rowmask,
    # ldmask and rdmask. all set bits of 'safe'
    # indicates the safe column index for queen
    # placement of this iteration for row index(row).
    safe = all_rows_filled & (~(rowmask |
                                ldmask | rdmask))
    while (safe > 0):
        # extracts the right-most set bit
        # (safe column index) where queen
        # can be placed for this row
        p = safe & (-safe)
        col = (int)(math.log(p)/math.log(2))
        board[row][col] = 'q'
        # this is very important:
        # we need to update rowmask, ldmask and rdmask
        # for next row as safe index for queen placement
        # will be decided by these three bit masks.
        # we have all three rowmask, ldmask and
        # rdmask as 0 in beginning. suppose, we are placing
        # queen at 1st column index at 0th row. rowmask, ldmask
        # and rdmask will change for next row as below:
        # rowmask's 1st bit will be set by or operation
        # rowmask = 00000000000000000000000000000010
        # ldmask will change by setting 1st
        # bit by or operation  and left shifting
        # by 1 as it has to block the next column
        # of next row because that will fall on left diagonal.
        # ldmask = 00000000000000000000000000000100
        # rdmask will change by setting 1st bit
        # by or operation and right shifting by 1
        # as it has to block the previous column
        # of next row because that will fall on right diagonal.
        # rdmask = 00000000000000000000000000000001
        # these bit masks will keep updated in each
        # iteration for next row
        solveboard(board, row 1, rowmask | p,
                   (ldmask | p) << 1, (rdmask | p) >> 1)
        # reset right-most set bit to 0 so, next
        # iteration will continue by placing the queen
        # at another safe column index of this row
        safe = safe & (safe-1)
        # backtracking, replace 'q' by ' '
        board[row][col] = ' '
# program to print board
def printboard(board):
    for row in board:
        print("|"   "|".join(row)   "|")
# driver code
def main():
    n = 4  # board size
    board = []
    for i in range(n):
        row = []
        for j in range(n):
            row.append(' ')
        board.append(row)
    rowmask = 0
    ldmask = 0
    rdmask = 0
    row = 0
    # function call
    result.clear()
    solveboard(board, row, rowmask, ldmask, rdmask)
    result.sort()
    print(result)
if __name__ == "__main__":
    main()
# this code is contributed by nikhil vinay

output

[2 4 1 3 ][3 1 4 2 ]

本文由 供稿。如果你喜欢 geeksforgeeks 并想投稿,你也可以使用写一篇文章或者把你的文章邮寄到 review-team@geeksforgeeks.org。看到你的文章出现在极客博客pg电子试玩链接主页上,帮助其他极客。

如果你发现任何不正确的地方,或者你想分享更多关于上面讨论的话题的信息,请写评论。