# My C# Solution

• ``````public int TotalNQueens(int n)
{
char[,] position = new char[n, n];
if (n <= 0)
return 0;
int totalSolution = 0;
totalSolution = Solve(position, n, 0, 0, totalSolution);

}

/// <summary>
/// Recursive method to be called to solve the problem step by step
/// </summary>
/// <param name="position">2D array to set the position of the Queens in 2D</param>
/// <param name="n">size of the board</param>
/// <param name="count">count of the queens placed on the board</param>
/// <param name="row">current row number</param>
/// <param name="totalSolution">count of the total solution found</param>
public int Solve(char[,] position, int n, int count, int row, int totalSolution)
{
// if each row/column has a Queen
if (count == n)
{
totalSolution++;
position = new char[n, n];
}

for (int j = 0; j < n; j++)
{
// check if this place is suitable to place the Queen
if (IsValid(position, n, row, j))
{
position[row, j] = 'Q';
count++;
// find place for next Queen in next row.
totalSolution = Solve(position, n, count, row + 1, totalSolution);
count--;
position[row, j] = '.';
}
}

}

/// <summary>
/// Method to check if the selected row and column is suitable to place next Queen.
/// </summary>
/// <param name="arr">2D array having all Queens placed until now.</param>
/// <param name="length">size of the board</param>
/// <param name="row">row number</param>
/// <param name="col">column number</param>
/// <returns>true if place is valid</returns>
public bool IsValid(char[,] arr, int length, int row, int col)
{
int i, j;

// check Queen in row
for (i = 0; i < length; i++)
{
if (arr[row, i] == 'Q')
return false;
}

// check Queen in column
for (i = 0; i < length; i++)
{
if (arr[i, col] == 'Q')
return false;
}

// check top left to bottom right diagonal
i = row;
j = col;
while (i > 0 && j > 0)
{
i--;
j--;
}

while (i < length && j < length)
{
if (arr[i, j] == 'Q')
return false;
i++;
j++;
}

// check bottom left to top right
i = row;
j = col;
while (i < length - 1 && j > 0)
{
i++;
j--;
}

while (i >= 0 && j < length)
{
if (arr[i, j] == 'Q')
return false;
i--;
j++;
}

return true;
}
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.