2 Copyright (c) 2006 Paolo Capriotti <p.capriotti@sns.it>
3 (c) 2006 Maurizio Monge <maurizio.monge@kdemail.net>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
29 template<typename T1
> friend class Grid
;
31 Grid(int sizeX
, int sizeY
, const T
& defaultValue
)
32 : sizeX(sizeX
), sizeY(sizeY
) {
33 board
.resize(sizeX
* sizeY
, defaultValue
);
36 Grid(int sizeX
, int sizeY
)
37 : sizeX(sizeX
), sizeY(sizeY
) {
38 board
.resize(sizeX
* sizeY
);
41 Grid(const Grid
& other
)
42 : sizeX(other
.sizeX
), sizeY(other
.sizeY
)
43 , board(other
.board
) { }
45 template <typename T1
>
46 Grid(const Grid
<T1
>& other
)
47 : sizeX(other
.getSize().x
), sizeY(other
.getSize().y
) {
48 board
.resize(sizeX
* sizeY
);
49 for(int i
=sizeX
* sizeY
-1; i
>=0;i
--)
50 board
[i
] = other
.board
[i
];
53 Point
getSize() const {
54 return Point(sizeX
, sizeY
);
57 void changeSize(int x
, int y
) {
60 board
.resize(sizeX
* sizeY
);
63 const T
& operator[](Point p
) const {
66 return board
[p
.x
+ p
.y
* sizeX
];
68 T
& operator[](Point p
) {
71 return board
[p
.x
+ p
.y
* sizeX
];
74 /** \return the nth point in the grid, that is not guaranteed to be valid */
75 Point
nTh(int index
) const { return Point(index
%sizeX
, index
/sizeX
); }
77 Point
first() const { return Point(0,0); }
78 Point
last() const { return Point(sizeX
-1, sizeY
-1); }
80 Point
next(const Point
& p
) const {
82 return Point(0, p
.y
+1);
84 return Point(p
.x
+1, p
.y
);
86 bool valid(const Point
& p
) const {
87 return (0 <= p
.x
) && (p
.x
< sizeX
) && (0 <= p
.y
) && (p
.y
< sizeY
);
90 bool operator==(const Grid
& g
) const {
91 if(g
.sizeX
!= sizeX
|| g
.sizeY
!= sizeY
)
93 for(unsigned int i
=0;i
<board
.size();i
++)
94 if(board
[i
].operator!=(g
.board
[i
]))
99 bool operator!=(const Grid
& g
) const {
100 return !(*this == g
);
103 PathInfo
path(const Point
& from
, const Point
& to
) const {
104 Point delta
= to
- from
;
105 PathInfo::Direction direction
;
108 direction
= PathInfo::Vertical
;
109 else if (delta
.y
== 0)
110 direction
= PathInfo::Horizontal
;
111 else if (delta
.x
== delta
.y
)
112 direction
= PathInfo::Diagonal1
;
113 else if (delta
.x
== -delta
.y
)
114 direction
= PathInfo::Diagonal2
;
116 direction
= PathInfo::Undefined
;
119 if (direction
!= PathInfo::Undefined
) {
120 Point step
= delta
.normalizeInfinity();
121 Point position
= from
;
122 while ((position
+= step
) != to
) {
123 if((*this)[position
].operator!())
129 return PathInfo(direction
, num_obs
);