forked from benjyberk/ADP-ex4
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGridMap.cpp
107 lines (95 loc) · 2.87 KB
/
GridMap.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
//
// Benjy Berkowicz - 336182589
// Advanced Programming 2016-2017 Bar Ilan
//
#include "GridMap.h"
#include <algorithm>
using namespace std;
/**
* Initializes the 2d array to a given size
* @param width width of the array
* @param height height of the array
*/
GridMap::GridMap(int width, int height, vector<Point> inputObstacles) {
obstacles = inputObstacles;
maxWidth = width;
maxHeight = height;
// The array is constructed such that the point 0,0 is at [0][height-1]
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
Point* tempPoint = new Point(i, height - j - 1);
GraphSquare* tempGraphSquare = new GraphSquare(tempPoint);
tempGraphSquare->distanceFromSource = -1;
grid[i][height - j - 1] = tempGraphSquare;
}
}
}
/**
* The function searches for neighbours of a given point, checking essentially if the point is at
* a corner, and if so skipping that neighbour.
* @param xpos the x position of the node
* @param ypos the y position of the node
*/
vector<GraphSquare *> GridMap::getNeighbours(Point find) {
std::vector<Point>::iterator finder;
int xpos = find.x;
int ypos = find.y;
// An array of the neighbours to be created is initialized
vector<GraphSquare *> adjacent;
// Each check makes sure that the neighbour to be added actually exists
if ((xpos - 1) > -1) {
adjacent.push_back(grid[xpos - 1][ypos]);
}
if ((ypos + 1) < maxHeight) {
adjacent.push_back(grid[xpos][ypos + 1]);
}
if ((xpos + 1) < maxWidth) {
adjacent.push_back(grid[xpos + 1][ypos]);
}
if ((ypos - 1) > -1) {
adjacent.push_back(grid[xpos][ypos - 1]);
}
for (int i = 0; i < adjacent.size(); i++) {
int found = 0;
for (int j = 0; j < obstacles.size(); j++) {
Point a = *(adjacent[i]->gridLocation);
Point b = obstacles[j];
if (a == b) {
found = 1;
break;
}
}
if (found) {
adjacent.erase(adjacent.begin() + i);
}
}
// The constructed array is returned
return adjacent;
}
/**
* Returns a GraphSquare at a specified point
* @param xpos x position of the point
* @param ypos y position of the point
* @return the requested GraphSquare
*/
GraphSquare* GridMap::getNode(Point find) {
return grid[find.x][find.y];
}
/**
* The destructor loops through the 2d array, freeing all memory.
*/
GridMap::~GridMap() {
for (int i = 0; i < maxWidth; i++) {
for (int j = 0; j < maxHeight; j++) {
delete grid[i][j];
}
}
}
void GridMap::reset() {
for (int i = 0; i < maxWidth; i++) {
for (int j = 0; j < maxHeight; j++) {
grid[i][maxHeight - j - 1]->distanceFromSource = -1;
grid[i][maxHeight - j - 1]->predecessor = 0;
}
}
}