// C++ program to solve Rat in a Maze problem using backtracking #include using namespace std; bool estDisponible(const vector> &maze, int i, int j) { // si {i,j} est en dehors de la grille ou bloquée, retourner Faux. int m = maze.size(), n = maze[0].size(); return (i >= 0 && i < m && j >= 0 && j < n && maze[i][j] == 1); } // estDisponible() // fonction récursive de backtracking. bool chercherCheminRecursive(const vector> &maze, int i, int j, vector> &sol) { int m = maze.size(), n = maze[0].size(); // si on a atteint le but if(i == m - 1 && j == n - 1) { sol[i][j] = 1; return true; } // sinon : // vérifier si maze[i][j] est valide if(estDisponible(maze, i, j) == true) { // marquer {i,j} comme partie de la solution sol[i][j] = 1; // avancer vers le bas if(chercherCheminRecursive(maze, i + 1, j, sol) == true) return true; // si ça n'a rien donné, essayer vers la droite if(chercherCheminRecursive(maze, i, j + 1, sol) == true) return true; // sinon : backtracking // on défait {i,j} comme partie de la solution sol[i][j] = 0; return false; } else // maze[i][j] non valide { return false; } } // chercherCheminRecursive() // affichage d'une solution void afficherSolution(const vector> &sol) { for(size_t i = 0; i < sol.size(); i++, cout << '\n') for(size_t j = 0; j < sol[0].size(); j++) cout << sol[i][j] << ' '; } // afficherSolution() // résolution utilisant le backtracking bool chercherChemin(const vector> &maze) { int m = maze.size(), n = maze[0].size(); auto solution = vector>(m, vector(n, 0)); cout << '\n'; if(chercherCheminRecursive(maze, 0, 0, solution) == false) { cout << "Aucune solution.\n"; return false; } else { afficherSolution(solution); return true; } } // chercherChemin() // Programme principal. int main() { int T = 0; // nombre de testcases cin >> T; for(int t = 0; t < T; t++) // pour chaque testcase { // Lecture des données d'entrée int M = 0, N = 0; // taille du labyrinthe cin >> M >> N; auto labyrinthe = vector>(M, vector(N)); for(int i = 0; i < M; i++) for(int j = 0; j < N; j++) cin >> labyrinthe[i][j]; // Traitement du problème chercherChemin(labyrinthe); } return 0; } // main()