File tree Expand file tree Collapse file tree 1 file changed +76
-0
lines changed Expand file tree Collapse file tree 1 file changed +76
-0
lines changed Original file line number Diff line number Diff line change
1
+ // N Queens Problem - Leetcode
2
+ // https://leetcode.com/problems/n-queens/
3
+ class Solution
4
+ {
5
+ public:
6
+ bool isSafe (int n, int row, int col, vector<string> board)
7
+ {
8
+ int dr = row;
9
+ int dc = col;
10
+ while (row >= 0 && col >= 0 )
11
+ {
12
+ if (board[row][col] == ' Q' )
13
+ {
14
+ return false ;
15
+ }
16
+ row--;
17
+ col--;
18
+ }
19
+ col = dc;
20
+ row = dr;
21
+ while (col >= 0 )
22
+ {
23
+ if (board[row][col] == ' Q' )
24
+ {
25
+ return false ;
26
+ }
27
+ col--;
28
+ }
29
+ row = dr;
30
+ col = dc;
31
+ while (row < n && col >= 0 )
32
+ {
33
+ if (board[row][col] == ' Q' )
34
+ {
35
+ return false ;
36
+ }
37
+ row++;
38
+ col--;
39
+ }
40
+
41
+ return true ;
42
+ }
43
+ void solve (int n, int col, vector<string> &board, vector<vector<string>> &ans)
44
+ {
45
+ if (col == n)
46
+ {
47
+ ans.push_back (board);
48
+ return ;
49
+ }
50
+
51
+ for (int row = 0 ; row < n; row++)
52
+ {
53
+ if (isSafe (n, row, col, board))
54
+ {
55
+ board[row][col] = ' Q' ;
56
+
57
+ solve (n, col + 1 , board, ans);
58
+
59
+ board[row][col] = ' .' ;
60
+ }
61
+ }
62
+ }
63
+ vector<vector<string>> solveNQueens (int n)
64
+ {
65
+ vector<vector<string>> ans;
66
+ vector<string> board (n);
67
+ string s (n, ' .' );
68
+ for (int i = 0 ; i < n; i++)
69
+ {
70
+ board[i] = s;
71
+ }
72
+ solve (n, 0 , board, ans);
73
+
74
+ return ans;
75
+ }
76
+ };
You can’t perform that action at this time.
0 commit comments