how backtracks work

leetCode 50 (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.

solution: each potentional position for a queen should satisfy no attach, then traverse the 2D grids to find out all good positions; it requires to find all possible combinations, so recursive call will be used also.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
bool one_queen_visited(int** mat, int n, pair<int, int>& queen_idx)
{
int row = queen_idx.first ;
int col = queen_idx.second;
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
if(mat[row][j] == 0)
mat[row][j] = 1;
else if(mat[row][j] == 100)
return false;
}
if(mat[i][col] == 0)
mat[i][col] = 1;
else if(mat[i][col] == 100)
return false;
}
//for left leaning
for(int i=row, j=col; i>=0 && j>=0; i--, j--)
{
if(mat[i][j] == 0)
mat[i][j] = 1;
else if(mat[i][j] == 100)
return false;
}
for(int i=row, j=col; i<n && j<n; i++, j++)
{
if(mat[i][j] == 0)
mat[i][j] = 1;
else if(mat[i][j] == 100)
return false;
}
//for right leaning
//down
for(int i=row, j=col; i<n && j>=0; i++, j--)
{
if(mat[i][j] == 0)
mat[i][j] = 1;
else if(mat[i][j] == 100)
return false;
}
//up
for(int i=row, j=col; i>=0 && j<n; i--, j++)
{
if(mat[i][j] == 0)
mat[i][j] = 1;
else if(mat[i][j] == 100)
return false;
}
mat[row][col] = 100; //queen location marked as 100
return true;
}
int backtrack = 0;
void sol(int** mat, int n, int start_j=0)
{
std::pair<int, int> idx;
vector<pair<int, int>> queens;
vector< vector<pair<int, int>> > queens_v;
if(start_j > n) return ; //end of recursive
for(int i=0; i<n; i++)
{
for(int j= ((i==0)? max(start_j, 0) : 0); j<n; j++)
{
idx = std::make_pair(i, j);
if(one_queen_visited(mat, n, idx)) // find a fit queen position, store into queens
{
queens.push_back(idx);
}
}
}
if(queens.size() == n)
{
queens_v.push_back(queens);
int** mat_copy = new int*[n] ;
for(int i=0; i<n; i++)
{
mat_copy[i] = new int[n]();
}
for(int i=0; i<queens.size(); i++)
{
idx = queens[i];
mat_copy[idx.first][idx.second] = 1 ;
}
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
cout<< mat_copy[i][j] << ' ' ;
cout << endl;
}
}
clean_mat(mat, n);
sol(mat, n, ++backtrack);
}

I did actually new memory in C++ as following:

1
2
3
int** mat = (int**) new(n * sizeof(int*));
for(int i=0; i<n; i++)
mat[i] = (int*) new( n * sizeof(int));

which failed, then realized only malloc works in this way.