N-Queens

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.

思路:

  dfs + 回溯 常用模板

我的代码:

public class Solution {

    public List<String[]> solveNQueens(int n) {

        if(n <= 0)  return rst;

        char[][] board = new char [n][n];

        for(int i = 0; i < n; i++)

        {

            for(int j = 0; j < n; j++)

            {

                board[i][j] = '.';

            }

        }

        placeQueens(board, 0, n);

        return rst;

    }

    private List<String[]> rst = new ArrayList<String[]>();

    public void placeQueens(char[][] board, int row, int n)

    {

        //success

        if(row == n)

        {

            String[] strings = new String[n];

            for(int i = 0; i < n ; i++)

            {

                strings[i] = new String(board[i]);

            }

            rst.add(strings);

            return;

        }

        for(int j = 0; j < n; j++)

        {

            if(canPut(board, row, j, n))

            {

                board[row][j] = 'Q';

                placeQueens(board, row + 1, n);

                board[row][j] = '.';

            }

        }

    }

    public boolean canPut(char [][]board, int x, int y, int n)

    {

        if(x == 0)  return true;

        for(int row = 0; row <= x - 1; row++)

        {

            for(int col = 0; col < n; col++)

            {

                char c = board[row][col];

                if(c == '.') continue;

                else

                {

                    if(y == col) return false;

                    if(col + row == y + x) return false;

                    if(col - row == y - x) return false;

                }

            }

        }

        return true;

    }

}
View Code

 

你可能感兴趣的:(UE)