-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolve.js
96 lines (85 loc) · 2.54 KB
/
solve.js
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
function solveSudoku(algo, board) {
// Prepare data types for all algorithms based on user choice
let queue;
let stack;
switch (algo) {
case "BFS":
queue = [board];
break;
case "DFS":
case "Greedy":
stack = [board];
break;
default:
throw new Error("Invalid algorithm specified");
}
let delay = 10; // Delay time (in milliseconds)
function solve(currentBoard) {
let emptyCell = findEmptyCell(currentBoard);
if (!emptyCell) {
// Puzzle solved successfully
updateBoardAI(currentBoard, true);
printValid();
return currentBoard;
}
if (algo === "BFS" && queue.length === 0) {
return null; // No solution found (BFS specific)
}
let [row, col] = emptyCell;
if (algo === "Greedy") {
let nextCell = findNextCellGreedy(currentBoard);
row = nextCell[0];
col = nextCell[1];
}
for (let num = 1; num <= board.length; num++) {
if (isValidMove(currentBoard, row, col, num)) {
let newBoard = copyBoard(currentBoard);
newBoard[row][col] = num;
if (algo === "BFS") {
queue.push(newBoard);
} else {
stack.push(newBoard); // For DFS, DLS, and Greedy
}
}
}
let nextBoard;
switch (algo) {
case "BFS":
nextBoard = queue.shift();
break;
case "DFS":
case "Greedy":
nextBoard = stack.pop();
break;
default:
throw new Error("Invalid algorithm specified");
}
updateBoardAI(currentBoard, true); // Can be called before or after pushing to stack
return setTimeout(() => solve(nextBoard), delay); // Recursive call with next state and depth for BFS/DFS/DLS/Greedy
}
// Start the recursive step with a delay
return setTimeout(() => solve(board), delay);
}
function findNextCellGreedy(board) {
// This function should find the empty cell with the fewest possible valid moves.
// Here's an example implementation:
let minValidMoves = board.length;
let minValidCell = null;
for (let row = 0; row < board.length; row++) {
for (let col = 0; col < board.length; col++) {
if (board[row][col] === 0) {
let validMoves = 0;
for (let num = 1; num <= board.length; num++) {
if (isValidMove(board, row, col, num)) {
validMoves++;
}
}
if (validMoves < minValidMoves) {
minValidMoves = validMoves;
minValidCell = [row, col];
}
}
}
}
return minValidCell; // Return the cell with the fewest valid moves
}