How can we lower the time complexity of this solution of NxN queens matrix validator? I have this solution while I check every row and every column and every diagonal of the matrix. If every row and column has exactly 1 queen, and the matrix has no more than 1 queen the output is true. This solution works but I think it's brute force.
public static boolean solveMatrix(int[][] matrix) {
int row, col;
int rowCount = matrix.length;
int columnCount = matrix[0].length;
int counter = 0;
// Checking if there is 1 queen per row
for (int i = 0; i < 8; i++) {
counter = 0;
for (int j = 0; j < 8; j++) {
if (matrix[i][j] == 1) {
counter++;
}
}
if (counter != 1) {
return false;
}
}
// Checking if there is 1 queen per column
for (int i = 0; i < 8; i++) {
counter = 0;
for (int j = 0; j < 8; j++) {
if (matrix[j][i] == 1) {
counter++;
}
}
if (counter != 1) {
return false;
}
}
// Checking first side diagonals
for (int k = 0; k < rowCount; k++) {
counter = 0;
for (row = k, col = 0; row >= 0 && col < columnCount; row--, col++) {
if (matrix[row][col] == 1) {
counter++;
}
}
if (counter > 1) {
return false;
}
}
// Checking first side diagonals
for (int k = 1; k < columnCount; k++) {
counter = 0;
for (row = rowCount - 1, col = k; row >= 0 && col < columnCount; row--, col++) {
if (matrix[row][col] == 1) {
counter++;
}
}
if (counter > 1) {
return false;
}
}
// Checking second side diagonals
for (int k = rowCount - 1; k >= 0; k--) {
counter = 0;
for (row = k, col = columnCount - 1; row >= 0 && col >= 0; row--, col--) {
if (matrix[row][col] == 1) {
counter++;
}
}
if (counter > 1) {
return false;
}
}
// Checking second side diagonals
for (int k = rowCount - 1; k >= 0; k--) {
counter = 0;
for (row = k, col = columnCount - 1; row >= 0 && col >= 0; row--, col--) {
if (matrix[row][col] == 1) {
counter++;
}
}
if (counter > 1) {
return false;
}
}
return true;
}