Skip to content

Commit 1d4e7e2

Browse files
authored
Merge pull request #1681 from a93a/51
Create 0051-n-queens-kt
2 parents 8f902db + 7daac18 commit 1d4e7e2

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

kotlin/0051-n-queens.kt

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
class Solution {
2+
fun solveNQueens(n: Int): List<List<String>> {
3+
val cols = HashSet<Int>() //keep track of used columns, we iterate rows
4+
val posDia = HashSet<Int>() //...of positive diagonals R+C
5+
val negDia = HashSet<Int>() //...of negative diagonals R-C
6+
val temp: ArrayList<ArrayList<String>> = arrayListOf() // to hold our temporary distinct solution
7+
val res: ArrayList<ArrayList<String>> = arrayListOf() // result with each distinct solutin where each input is a solution
8+
fillWithQueens(0,n,res,cols,posDia,negDia,temp)
9+
return res
10+
}
11+
private fun fillWithQueens(
12+
row: Int,
13+
n: Int,
14+
res: ArrayList<ArrayList<String>>,
15+
cols: HashSet<Int>,
16+
posDia: HashSet<Int>,
17+
negDia: HashSet<Int>,
18+
board: ArrayList<ArrayList<String>>
19+
){
20+
//if we have filled the whole board with queens
21+
if(row == n){
22+
val complete: ArrayList<String> = arrayListOf()
23+
for(i in 0..n-1){
24+
val joined = board[i].joinToString(separator = "")
25+
complete.add(joined)
26+
}
27+
res.add(complete)
28+
return
29+
}
30+
for(column in 0 until n){
31+
if(cols.contains(column) || posDia.contains(row+column) || negDia.contains(row-column))
32+
continue
33+
val temp = tempRow(n)
34+
board.add(temp)
35+
cols.add(column)
36+
posDia.add(row+column)
37+
negDia.add(row-column)
38+
board[row][column] = "Q"
39+
fillWithQueens(row+1,n,res,cols,posDia,negDia,board)
40+
cols.remove(column)
41+
posDia.remove(row+column)
42+
negDia.remove(row-column)
43+
board[row][column] = "."
44+
}
45+
}
46+
private fun tempRow(n: Int): ArrayList<String>{
47+
val temp: ArrayList<String> = arrayListOf()
48+
repeat(n){
49+
temp.add(".")
50+
}
51+
return temp
52+
}
53+
}

0 commit comments

Comments
 (0)