-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMaze.cpp
83 lines (73 loc) · 1.42 KB
/
Maze.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include "Maze.h"
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
static const int MOV[4][2]={{-1,0},{0,-1},{0,1},{1,0}};
static bool isValid(int i,int j,int dim){
return i>=0 && j>=0 && i<dim && j<dim;
}
static void shuffle(int arr[],int size){
for (int i=0;i<size;i++){
int pos=rand()%size;
int tmp=arr[pos];
arr[pos]=arr[i];
arr[i]=tmp;
}
}
Maze::Maze(int dim,int i,int j){
if(!isValid(i,j,dim)){
throw 0;
}
this->m= new Matrix<Cell>(dim,dim);
this->dim=dim;
srand(time(0));
apply(i,j);
}
Maze::~Maze(){
delete this->m;
}
bool Maze::apply(int i,int j){
Cell& current=this->m->get(i,j);
current.mark();
if(i==(this->dim-1)&&j==(this->dim-1)){
current.setSolution();
return true;
}
bool retval=false;
int dirs[]={0,1,2,3};
shuffle(dirs,4);
for(int k=0;k<4;k++){
int n_i=i+MOV[dirs[k]][0],n_j=j+MOV[dirs[k]][1];
if(!isValid(n_i,n_j,this->dim))
continue;
Cell& other=this->m->get(n_i,n_j);
if(!other.isMarked()){
switch(dirs[k]){
case 0:
current.destroyUp();
other.destroyDown();
break;
case 1:
current.destroyLeft();
other.destroyRight();
break;
case 2:
current.destroyRight();
other.destroyLeft();
break;
case 3:
current.destroyDown();
other.destroyUp();
break;
default:
break;
}
if(apply(n_i,n_j)){
retval=true;
current.setSolution();
}
}
}
return retval;
}