Skip to content

Instantly share code, notes, and snippets.

@AdrianoPereira
Created September 17, 2017 21:21
Show Gist options
  • Save AdrianoPereira/e7b5e780de1e127cea988e434c952df0 to your computer and use it in GitHub Desktop.
Save AdrianoPereira/e7b5e780de1e127cea988e434c952df0 to your computer and use it in GitHub Desktop.
Backtracking para sair do labirinto
#include <bits/stdc++.h>
using namespace std;
#define L 4
#define C 4
/*Não foi necessário
int cx[] = {1, -1, 0, 0};
int cy[] = {0, 0, 1, -1};
*/
int matriz[L][C] = {
{0,0,1,0},
{1,0,0,0},
{1,1,0,1},
{1,1,0,0},
};
bool visitados[L+1][C+1];
/*Nao foi necessario
bool areaDisponivel(int x, int y){
if(x>=L || x<0 || y>=C || y<0)
return false;
if(matriz[x][y] == 1)
return false;
return true;
}
*/
void percorrer(int x, int y){
if(x>=0 && y>=0 && x<L && y<C){
visitados[x][y] = true;
cout << "Linha: " << x+1 << " - Coluna: " << y+1 << endl;
if(x==0 && y==0){
cout << "Fim do Labirinto!" << endl;
}else{
if(x+1<L && matriz[x+1][y] == 0 && !visitados[x+1][y]){
percorrer(x+1, y);
}
if(x-1>=0 && matriz[x-1][y] == 0 && !visitados[x-1][y]){
percorrer(x-1, y);
}
if(y+1<C && matriz[x][y+1] == 0 && !visitados[x][y+1]){
percorrer(x, y+1);
}
if(y-1>=0 && matriz[x][y-1] == 0 && !visitados[x][y-1]){
percorrer(x, y-1);
}
}
}
}
int main(){
memset(visitados, false, sizeof visitados);
percorrer(3, 3);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment