-
Notifications
You must be signed in to change notification settings - Fork 0
/
grid.h
96 lines (85 loc) · 2.02 KB
/
grid.h
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
#ifndef GRID_H_
#define GRID_H_
#include <algorithm>
#include <string.h>
#include "Location.h"
class State;
template <typename Passable> class GridBfs;
extern int getStateRows(const State &state);
extern int getStateCols(const State &state);
template <typename T>
class Grid
{
public:
Grid() : rows(0), cols(0), data(0) { }
Grid(const Grid &other)
: rows(other.rows), cols(other.cols), data(0)
{
data = new T[rows * cols];
std::copy(other.data, other.data + rows * cols, data);
}
~Grid() { delete data; }
template <typename U>
void init(const Grid<U> &grid)
{
init(grid.rows, grid.cols);
}
void init(const State &state)
{
init(getStateRows(state), getStateCols(state));
}
void init(int r, int c)
{
if (!data) {
rows = r;
cols = c;
data = new T[rows * cols];
reset();
}
}
void reset()
{
std::fill(data, data + rows * cols, T());
}
T & operator () (const Location &loc)
{
return data[loc.row * cols + loc.col];
}
T & operator () (int r, int c)
{
return data[r * cols + c];
}
const T & operator () (const Location &loc) const
{
return data[loc.row * cols + loc.col];
}
const T & operator () (int r, int c) const
{
return data[r * cols + c];
}
T * operator [] (const int row)
{
return data + row * cols;
}
const T * operator [] (const int row) const
{
return data + row * cols;
}
Grid & operator = (const Grid &rhs)
{
if (data == 0 || rows != rhs.rows || cols != rhs.cols) {
rows = rhs.rows;
cols = rhs.cols;
delete data;
data = new T[rows * cols];
}
copy(rhs.data, rhs.data + rows * cols, data);
return *this;
}
protected:
template <typename> friend class GridBfs;
template <typename> friend class Grid;
int rows, cols;
T *data;
};
#endif /* GRID_H_ */