[Leetcode] N Queens in Java

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.."]
]
Thoughts: with recursive check(DFS) to find the solution and add each solution to result as ArrayList<String>

 public class Solution {  
   public List<List<String>> solveNQueens(int n) {  
     List<List<String>> result = new ArrayList<List<String>>();  
     int[] location = new int[n];  
     dfs(result, location, 0, n);  
     return result;  
   }  
   public void dfs(List<List<String>> result, int[] loc, int curRow, int n){  
     if (curRow == n){  
       addResult(result, loc, n);  
     } else {  
       for (int i=0; i<n; i++){  
         loc[curRow] = i;  
         if (isValid(loc, curRow)){  
           dfs(result, loc, curRow+1, n);  
         }  
       }  
     }  
   }  
   public boolean isValid(int[] loc, int curRow){  
     for (int i=0; i<curRow; i++){  
       if (loc[curRow] == loc[i] || Math.abs(loc[curRow] - loc[i]) == (curRow - i)){  
         return false;  
       }  
     }  
     return true;    
   }  
   public void addResult(List<List<String>> result, int[] loc, int n){  
     List<String> sol= new ArrayList<String>();  
     for (int i=0; i<n; i++){  
       StringBuilder sb = new StringBuilder();  
       for (int j=0; j<n; j++){  
         if (loc[i] == j){  
           sb.append("Q");  
         } else {  
           sb.append(".");  
         }  
       }  
       sol.add(sb.toString());  
     }  
     result.add(sol);  
   }  
 }  

No comments :

Post a Comment