Leetcode-n-queens

Source: Internet
Author: User

Topic:

The n-queens Puzzle is the problem of placing N Queens on a nxn chessboard such that No, Queens attack.

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 Indi Cate a queen and an empty space respectively.

For example,
There exist-distinct solutions to the 4-queens puzzle:

[ [". Q.. ",  //solution 1  " ... Q ",  " Q ... ",".  . Q. "], ["]. Q. ",  //Solution 2  " Q ... ",  " ... Q ",  ". Q.. "]

Ideas:

1) recursion, set the position of the oblique direction to the "Forbidden" area at each recursion

 Packagerecursion;Importjava.util.ArrayList;Importjava.util.List; Public classNqueens { PublicList<list<string>> Solvenqueens (intN) {Char[] board =New Char[N][n];  for(inti = 0; I < n; ++i) { for(intj = 0; J < N; ++j) {Board[i][j]= '. '; }} List<List<String>> res =NewArraylist<list<string>>(); Solve (res,0, board, N); returnRes; }        Private voidSolve (list<list<string>> res,intRowChar[] board,intN) {if(Row >=N) {List<String> record =NewArraylist<string>();  for(inti = 0; I < n; ++i) {StringBuilder sb=NewStringBuilder ();  for(intj = 0; J < N; ++j) {if(board[i][j]! = ' Q ') Board[i][j]= '. ';                Sb.append (Board[i][j]);            } record.add (Sb.tostring ());            } res.add (record); return; }                 for(inti = 0; I < n; ++i) {if(Board[row][i] = = '. ') {                Char[] Cpyboard =Copyboard (board, N);                Setforbiddenarea (Cpyboard, row, I, n); Solve (res, row+ 1, Cpyboard, N); }        }    }        Private voidSetforbiddenarea (Char[] board,intIintJintN) {//Rows and Columns         for(intk = 0; K < n; ++k) {Board[i][k]= ' F '; BOARD[K][J]= ' F '; }        //Diagonal         for(intK = 1-n; K <= n-1; ++k) {if(i + k >= 0 && i + K < n && j + k >= 0 && j + K <N) board[i+ K][j + K] = ' F '; if(i + k >= 0 && i + K < n && j-k >= 0 && J-k <N) board[i+ k][j-k] = ' F '; } Board[i][j]= ' Q '; }        Private Char[] Copyboard (Char[] board,intN) {Char[] Cpyboard =New Char[N][n];  for(inti = 0; I < n; ++i) { for(intj = 0; J < N; ++j) Cpyboard[i][j]=Board[i][j]; }        returnCpyboard; }         Public Static voidMain (string[] args) {//TODO auto-generated Method StubNqueens n =NewNqueens (); List<List<String>> res = N.solvenqueens (4);  for(list<string>subres:res) {             for(String s:subres) System.out.print (s+ "\ T"); System.out.println ("\ n"); }    }}

2) use a one-dimensional array to store the position of Q for each line, I for line I, rows[i] for the position of Q.

 Packagerecursion;Importjava.util.ArrayList;Importjava.util.List; Public classNqueens { PublicList<list<string>> Solvenqueens (intN) {List<List<String>> res =NewArraylist<list<string>>(); int[] positions =New int[n]; Solve (positions, res,0, N); returnRes; }        Private voidSolveint[] positions, list<list<string>> Res,intRowintN) {if(Row = =N) {List<String> record =NewArraylist<string>();  for(inti = 0; I < n; ++i) {StringBuilder sb=NewStringBuilder ();  for(intj = 0; J < N; ++j) Sb.append (‘.‘); Sb.setcharat (Positions[i],' Q ');            Record.add (Sb.tostring ());        } res.add (record); } Else {             for(inti = 0; I < n; ++i) {if(IsValid (positions, row, i)) {Positions[row]=i; Solve (positions, res, row+ 1, N); }            }        }    }        Private BooleanIsValid (int[] positions,intRowintcandidate) {         for(inti = 0; i < row; ++i) {if(Positions[i] = = Candidate | | Math.Abs (i-row) = = Math.Abs (Positions[i]-candidate)) return false; }        return true; }         Public Static voidMain (string[] args) {//TODO auto-generated Method StubNqueens n =NewNqueens (); List<List<String>> res = N.solvenqueens (4);  for(list<string>subres:res) {             for(String s:subres) System.out.print (s+ "\ T"); System.out.println ("\ n"); }    }}

Leetcode-n-queens

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.