Advertisement
Fastrail08

Knight Tour Problem

Jun 3rd, 2025
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.96 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const vector<int> dx = {-2, -1, 1, 2, 2, 1, -1, -2};
  5. const vector<int> dy = {1, 2, 2, 1, -1, -2, -2, -1};
  6.  
  7. void knightTour(int row, int col, int cellVisited, vector<vector<int> > &chess, vector<string> &allValidKnightPaths){
  8.     //Invalid Path
  9.     if(row < 0 || row >= chess.size() || col < 0 || col >= chess.size() || chess[row][col]){
  10.         return;
  11.     }
  12.    
  13.     //Mark the current cell visited by the Knight
  14.     chess[row][col] = cellVisited;
  15.    
  16.     //base case
  17.     if(cellVisited == pow(chess.size(), 2)){
  18.         string validPath = "";
  19.         for(int i = 0; i < chess.size(); i++){
  20.             for(int j = 0; j < chess[0].size(); j++){
  21.                 validPath += to_string(chess[i][j]) + " ";
  22.             }
  23.             validPath += '\n';
  24.         }
  25.         allValidKnightPaths.push_back(validPath);
  26.         chess[row][col] = 0;
  27.         return;
  28.     }
  29.    
  30.     //Levels/States = each cell
  31.     //Options/Transitions = all the 8 moves
  32.    
  33.     //explore all 8 options for each cell
  34.     for(int k = 0; k < dx.size(); k++){
  35.         knightTour(row + dx[k], col + dy[k], cellVisited + 1, chess, allValidKnightPaths);
  36.     }
  37.    
  38.     // Backtrack from the current cell/mark unvisited
  39.     chess[row][col] = 0;
  40. }
  41.  
  42. int main() {
  43.     // your code goes here
  44.     int n;
  45.     cin >> n;
  46.    
  47.     vector<vector<int> > chess(n, vector<int>(n, 0));
  48.    
  49.     vector<string> allValidKnightPaths;
  50.    
  51.     // Start Knight Tour from each of the cell in chessboard, to generate all possible configurations
  52.     for(int i = 0; i < n; i++){
  53.         for(int j = 0; j < n; j++){
  54.             // here 1 is passed, as the current cell is marked as visited
  55.             knightTour(i, j, 1, chess, allValidKnightPaths);
  56.         }
  57.     }
  58.    
  59.     //print all valid knight paths
  60.     cout << "Total Paths: " << allValidKnightPaths.size() << '\n';
  61.     for(string path : allValidKnightPaths){
  62.         cout << path << '\n';
  63.     }
  64. }
  65.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement