Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit7d7f109

Browse files
authored
Enhance readability of KnightTour (TheAlgorithms#1572)
1 parent60443c7 commit7d7f109

File tree

1 file changed

+9
-6
lines changed

1 file changed

+9
-6
lines changed

‎Backtracking/KnightTour.js

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,13 @@
22

33
classOpenKnightTour{
44
constructor(size){
5+
// Constructor to initialize the chessboard and size
56
this.board=newArray(size).fill(0).map(()=>newArray(size).fill(0))
67
this.size=size
78
}
89

910
getMoves([i,j]){
10-
//helper function to get the valid moves of the knight from the current position
11+
//Helper function to get the valid moves of the knight from the current position
1112
constmoves=[
1213
[i+2,j-1],
1314
[i+2,j+1],
@@ -19,18 +20,19 @@ class OpenKnightTour {
1920
[i-1,j+2]
2021
]
2122

23+
// Filter out moves that are within the board boundaries
2224
returnmoves.filter(
2325
([y,x])=>y>=0&&y<this.size&&x>=0&&x<this.size
2426
)
2527
}
2628

2729
isComplete(){
28-
//helper function to check if the board is complete
30+
//Helper function to check if the board is complete
2931
return!this.board.map((row)=>row.includes(0)).includes(true)
3032
}
3133

3234
solve(){
33-
//function to find the solution for the given board
35+
//Function to find the solution for the given board
3436
for(leti=0;i<this.size;i++){
3537
for(letj=0;j<this.size;j++){
3638
if(this.solveHelper([i,j],0))returntrue
@@ -40,22 +42,23 @@ class OpenKnightTour {
4042
}
4143

4244
solveHelper([i,j],curr){
43-
//helper function for the main computation
45+
//Helper function for the main computation
4446
if(this.isComplete())returntrue
4547

48+
// Iterate through possible moves and attempt to fill the board
4649
for(const[y,x]ofthis.getMoves([i,j])){
4750
if(this.board[y][x]===0){
4851
this.board[y][x]=curr+1
4952
if(this.solveHelper([y,x],curr+1))returntrue
50-
//backtracking
53+
//Backtracking: If the solution is not found, reset the cell to 0
5154
this.board[y][x]=0
5255
}
5356
}
5457
returnfalse
5558
}
5659

5760
printBoard(output=(value)=>console.log(value)){
58-
//utility function to display the board
61+
//Utility function to display the board
5962
for(constrowofthis.board){
6063
letstring=''
6164
for(constelemofrow){

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp