Instructions
Requirements and Specifications
Source Code and Solution
#include
#include"maze.h"
using namespace std;
MazeElement::MazeElement() {
row = -1;
col = -1;
type = 0;
path = false;
distance = -1;
}
MazeElement::MazeElement(int _r, int _c, char _t) {
row = _r;
col = _c;
if (_t == '#') {
type = 0;
}
else if (_t == ' ') {
type = 1;
}
else {
type = 2;
}
distance = -1;
path = false;
}
int MazeElement::getType() {
return type;
}
int MazeElement::getDistance() {
return distance;
}
void MazeElement::setDistance(int _d) {
distance = _d;
}
bool MazeElement::isPath() {
return path;
}
void MazeElement::setPath(bool _p) {
path = _p;
}
char MazeElement::toChar() {
if (type == 2) {
return 'o';
}
else if (path) {
return '.';
}
else if (type == 0) {
return '#';
}
return ' ';
}
Maze::Maze(int _h, int _w) {
height = _h;
width = _w;
cells = new MazeElement*[height];
for (int i = 0; i
cells[i] = new MazeElement[width];
}
}
Maze::~Maze() {
for (int i = 0; i
delete[] cells[i];
}
delete[] cells;
}
void Maze::setCell(int _r, int _c, char _t) {
MazeElement me(_r, _c, _t);
cells[_r][_c] = me;
}
void Maze::print() {
for (int i = 0; i
for (int j = 0; j
cout << cells[i][j].toChar();
}
cout << endl;
}
}
void Maze::visit(int _r, int _c, int len) {
MazeElement me = cells[_r][_c];
if (cells[_r][_c].getDistance() < 0 || cells[_r][_c].getDistance() > len) {
cells[_r][_c].setDistance(len);
}
else {
return;
}
if(canVisit(_r+1, _c)){
visit(_r+1, _c, len + 1);
}
if(canVisit(_r, _c+1)){
visit(_r, _c+1, len + 1);
}
if(canVisit(_r-1, _c)){
visit(_r-1, _c, len + 1);
}
if(canVisit(_r, _c-1)){
visit(_r, _c-1, len + 1);
}
}
bool Maze::canVisit(int _r, int _c) {
if (_r < 0 || _r >= height || _c < 0 || _c >= width) {
return false;
}
if (cells[_r][_c].getType() == 0) {
return false;
}
return true;
}
void Maze::findPath(int _r, int _c) {
visit(_r, _c, 0);
int currR = -1;
int currC = -1;
for (int i = 0; i
for (int j = 0; j
if (cells[i][j].getType() == 2) {
currR = i;
currC = j;
}
}
}
while(currR != _r || currC != _c) {
int dist = cells[currR][currC].getDistance();
if(canVisit(currR+1, currC) && cells[currR+1][currC].getDistance() + 1 == dist){
currR++;
}
else if(canVisit(currR, currC+1) && cells[currR][currC+1].getDistance() + 1 == dist){
currC++;
}
else if(canVisit(currR-1, currC) && cells[currR-1][currC].getDistance() + 1 == dist){
currR--;
}
else if(canVisit(currR, currC-1) && cells[currR][currC-1].getDistance() + 1 == dist){
currC--;
}
cells[currR][currC].setPath(true);
}
print();
}