// Recherche d'un chemin dans un labyrinthe par backtracking #include using namespace std; // Fonction pour vérifier si une case est libre 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 (case en bas à droite) if(i == m - 1 && j == n - 1) { sol[i][j] = 1; return true; } // Sinon : // Vérifier si la case {i, j} est accessible if(estDisponible(maze, i, j) == true) { // Marquer {i,j} comme partie de la solution sol[i][j] = 1; // Aller vers le bas if(chercherCheminRecursive(maze, i + 1, j, sol) == true) return true; // ça a fonctionné en allant en bas // Si ça n'a rien donné, aller vers la droite if(chercherCheminRecursive(maze, i, j + 1, sol) == true) return true; // ça a fonctionné en allant à droite // Sinon : BACKTRACKING // On défait {i,j} comme partie de la solution sol[i][j] = 0; return false; } else // case {i, j} non accessible { return false; } } // chercherCheminRecursive() // Affichage d'une solution en marquant le chemin par des 1 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 (lignes, colonnes) 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]; // Résolution du problème chercherChemin(labyrinthe); } return 0; } // main()