Skip to content

Commit 268982e

Browse files
committed
Added N-Queens Problem Solver (console + web app)
1 parent 56835f6 commit 268982e

3 files changed

Lines changed: 170 additions & 2 deletions

File tree

utilities/N-Queens/N-Queens.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
def print_board(board, n):
2+
for row in board:
3+
print(" ".join("♛" if col else "⬜" for col in row))
4+
print()
5+
6+
def is_safe(board, row, col, n):
7+
# Check column
8+
for i in range(row):
9+
if board[i][col]:
10+
return False
11+
# Check upper-left diagonal
12+
for i, j in zip(range(row, -1, -1), range(col, -1, -1)):
13+
if board[i][j]:
14+
return False
15+
# Check upper-right diagonal
16+
for i, j in zip(range(row, -1, -1), range(col, n)):
17+
if board[i][j]:
18+
return False
19+
return True
20+
21+
def solve(board, row, n, solutions):
22+
if row == n:
23+
solutions.append([r[:] for r in board])
24+
return
25+
for col in range(n):
26+
if is_safe(board, row, col, n):
27+
board[row][col] = 1
28+
solve(board, row + 1, n, solutions)
29+
board[row][col] = 0
30+
31+
def main():
32+
n = int(input("Enter board size (n): "))
33+
board = [[0]*n for _ in range(n)]
34+
solutions = []
35+
solve(board, 0, n, solutions)
36+
37+
print(f"Total solutions for {n}-Queens: {len(solutions)}\n")
38+
for sol in solutions:
39+
print_board(sol, n)
40+
41+
if __name__ == "__main__":
42+
main()

web-app/index.html

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,14 @@ <h3>Morse Code</h3>
159159
<button class="btn-play">Try It</button>
160160
</div>
161161

162+
<div class="project-card" data-project="nqueens" data-category="utilities">
163+
<div class="card-icon">👑</div>
164+
<h3>N-Queen Problem Solver</h3>
165+
<p>Place queens safely on the board using backtracking.</p>
166+
<button class="btn-play">Try It</button>
167+
</div>
168+
169+
162170
<div class="project-card" data-category="utilities" data-project="tower-of-hanoi">
163171
<div class="card-icon">🗼</div>
164172
<h3>Tower of Hanoi</h3>

web-app/js/projects.js

Lines changed: 120 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@ function getProjectHTML(projectName) {
1919
'coordinate-polar-transform': getCoordinatePolarTransformHTML(),
2020
'derivative-calculator': getDerivativeCalculatorHTML(),
2121
'morse-code': getMorseCodeHTML(),
22-
'tower-of-hanoi': getTowerOfHanoiHTML()
22+
'tower-of-hanoi': getTowerOfHanoiHTML(),
23+
'nqueens' : getNQueensHTML()
2324
};
2425

2526
return projects[projectName] || '<h2>Project Coming Soon!</h2>';
@@ -44,7 +45,8 @@ function initializeProject(projectName) {
4445
'coordinate-polar-transform': initCoordinatePolarTransform,
4546
'derivative-calculator': initDerivativeCalculator,
4647
'morse-code': initMorseCode,
47-
'tower-of-hanoi': initTowerOfHanoi
48+
'tower-of-hanoi': initTowerOfHanoi,
49+
'nqueens' : initNQueens()
4850
};
4951

5052
if (initializers[projectName]) {
@@ -3308,6 +3310,122 @@ function initTowerOfHanoi() {
33083310

33093311
initTowers();
33103312
}
3313+
//N-Queens
3314+
function getNQueensHTML() {
3315+
return `
3316+
<div class="project-content">
3317+
<h2>👑 N-Queens Problem Solver</h2>
3318+
<div class="nqueens-container">
3319+
<div class="controls">
3320+
<label>
3321+
Board Size (N):
3322+
<input type="number" id="nValue" min="4" max="12" value="4">
3323+
</label>
3324+
<button class="btn-solve" id="solveNQueensBtn">🎯 Solve</button>
3325+
<button class="btn-reset" id="resetNQueens">Reset</button>
3326+
</div>
3327+
3328+
<div class="stats">
3329+
<div>Total Solutions: <span id="solutionCount">0</span></div>
3330+
</div>
3331+
3332+
<div id="nQueensOutput" class="solutions"></div>
3333+
</div>
3334+
</div>
3335+
3336+
<style>
3337+
.nqueens-container {
3338+
padding: 2rem;
3339+
text-align: center;
3340+
}
3341+
.controls {
3342+
display: flex;
3343+
gap: 1rem;
3344+
justify-content: center;
3345+
align-items: center;
3346+
margin-bottom: 1rem;
3347+
flex-wrap: wrap;
3348+
}
3349+
.controls input {
3350+
width: 80px;
3351+
padding: 0.5rem;
3352+
font-size: 1rem;
3353+
border: 2px solid var(--border-color);
3354+
border-radius: 8px;
3355+
background: var(--bg-color);
3356+
color: var(--text-color);
3357+
text-align: center;
3358+
}
3359+
.solutions {
3360+
margin-top: 1rem;
3361+
font-family: monospace;
3362+
white-space: pre;
3363+
text-align: left;
3364+
}
3365+
.btn-solve {
3366+
background: var(--success-color);
3367+
color: white;
3368+
border: none;
3369+
padding: 0.75rem 2rem;
3370+
border-radius: 50px;
3371+
cursor: pointer;
3372+
font-size: 1rem;
3373+
transition: var(--transition);
3374+
}
3375+
.btn-solve:hover {
3376+
transform: scale(1.05);
3377+
}
3378+
</style>
3379+
`;
3380+
}
3381+
function isSafe(board, row, col, n) {
3382+
for (let i = 0; i < row; i++) if (board[i][col]) return false;
3383+
for (let i=row, j=col; i>=0 && j>=0; i--, j--) if (board[i][j]) return false;
3384+
for (let i=row, j=col; i>=0 && j<n; i--, j++) if (board[i][j]) return false;
3385+
return true;
3386+
}
3387+
3388+
function solveNQueens(board, row, n, solutions) {
3389+
if (row === n) {
3390+
solutions.push(board.map(r => [...r]));
3391+
return;
3392+
}
3393+
for (let col = 0; col < n; col++) {
3394+
if (isSafe(board, row, col, n)) {
3395+
board[row][col] = 1;
3396+
solveNQueens(board, row+1, n, solutions);
3397+
board[row][col] = 0;
3398+
}
3399+
}
3400+
}
3401+
3402+
function initNQueens() {
3403+
const solveBtn = document.getElementById('solveNQueensBtn');
3404+
const resetBtn = document.getElementById('resetNQueens');
3405+
const output = document.getElementById('nQueensOutput');
3406+
const solutionCountEl = document.getElementById('solutionCount');
3407+
const nInput = document.getElementById('nValue');
3408+
3409+
function runSolver() {
3410+
let n = parseInt(nInput.value) || 4;
3411+
let board = Array.from({length:n}, () => Array(n).fill(0));
3412+
let solutions = [];
3413+
solveNQueens(board, 0, n, solutions);
3414+
3415+
solutionCountEl.textContent = solutions.length;
3416+
output.innerHTML = "";
3417+
solutions.forEach(sol => {
3418+
let grid = sol.map(row => row.map(cell => cell ? "♛" : "⬜").join(" ")).join("<br>");
3419+
output.innerHTML += `<pre>${grid}</pre><br>`;
3420+
});
3421+
}
3422+
3423+
solveBtn.addEventListener('click', runSolver);
3424+
resetBtn.addEventListener('click', () => {
3425+
output.innerHTML = "";
3426+
solutionCountEl.textContent = "0";
3427+
});
3428+
}
33113429

33123430
function getProjectileMotionHTML() {
33133431
return `

0 commit comments

Comments
 (0)