-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmazehandling.cpp
605 lines (506 loc) · 18.8 KB
/
mazehandling.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
#include "mazehandling.h"
#include "mazecell.h"
#include <stdlib.h>
#include <time.h>
#include <QPainter>
#include <stack>
#include <queue>
#include <chrono>
#include "mainwindow.h"
#define MAZE_ROWS 50
#define MAZE_COLS 50
#define CELL_SIZE 16
#define CELL_LINE 4
MazeHandling::MazeHandling(QWidget* parent) : QWidget(parent)
{
m_bMazeDataAvailable = false;
m_bSolveDataAvailable = false;
m_pStartCell = nullptr;
m_pEndCell = nullptr;
m_eSolveMazeType = SOLVEMAZE_DFS;
}
MazeHandling::~MazeHandling()
{
releaseMazeData();
}
void MazeHandling::releaseMazeData()
{
if (m_arrayMazeData.size() > 0)
{
for (size_t nRowIndex = 0; nRowIndex < MAZE_ROWS; ++nRowIndex)
{
if (m_arrayMazeData[nRowIndex].size() > 0)
{
for (size_t nColIndex = 0; nColIndex < MAZE_COLS; ++nColIndex)
{
Cell* cell = m_arrayMazeData[nRowIndex][nColIndex];
if (cell) delete cell;
}
m_arrayMazeData[nRowIndex].clear();
}
}
m_arrayMazeData.clear();
}
}
void MazeHandling::resetVisitedFlag()
{
if (m_arrayMazeData.size() > 0)
{
for (size_t nRowIndex = 0; nRowIndex < MAZE_ROWS; ++nRowIndex)
{
if (m_arrayMazeData[nRowIndex].size() > 0)
{
for (size_t nColIndex = 0; nColIndex < MAZE_COLS; ++nColIndex)
{
Cell* cell = m_arrayMazeData[nRowIndex][nColIndex];
if (cell) cell->setVisited(false);
}
}
}
}
}
void MazeHandling::setSolveMazeType(eSOLVEMAZE_TYPE eSolveMazeType)
{
m_eSolveMazeType = eSolveMazeType;
}
void MazeHandling::generateMazeData()
{
releaseMazeData();
m_bMazeDataAvailable = false;
// Generate new maze, also clear solved data of previous maze
m_bSolveDataAvailable = false;
m_pathSolvedData.clear();
m_pathTraversedData.clear();
for (int nRowIndex = 0; nRowIndex < MAZE_ROWS; ++nRowIndex)
{
std::vector<Cell*> vectorCol;
for (int nColIndex = 0; nColIndex < MAZE_COLS; ++nColIndex)
{
Cell* cell = new Cell(nRowIndex, nColIndex);
vectorCol.push_back(cell);
}
m_arrayMazeData.push_back(vectorCol);
}
carveDFS();
// Set start and end points
m_pStartCell = m_arrayMazeData[0][0];
m_pEndCell = m_arrayMazeData[MAZE_ROWS - 1][MAZE_COLS - 1];
m_bMazeDataAvailable = true;
this->update();
}
void MazeHandling::carveDFS()
{
/*
1. Choose the initial cell, mark it as visited and push it to the stack
2. While the stack is not empty
1. Pop a cell from the stack and make it a current cell
2. If the current cell has any neighbors which have not been visited
1. Push the current cell to the stack
2. Choose one of the unvisited neighbors
3. Remove the wall between the current cell and the chosen cell
4. Mark the chosen cell as visited and push it to the stack
*/
// Random a initial cell
srand(static_cast<unsigned int>(time(nullptr)));
size_t ranRowIndex = rand() % MAZE_ROWS;
size_t ranColIndex = rand() % MAZE_COLS;
Cell* randomCell = m_arrayMazeData[ranRowIndex][ranColIndex];
if (randomCell)
randomCell->setVisited(true);
std::stack<Cell*> stackVisitedCell;
stackVisitedCell.push(randomCell);
while( !stackVisitedCell.empty() )
{
Cell* curCell = stackVisitedCell.top();
NEIGHBOR_INFO infoNeighbor = getRandomGenNeighborDir(curCell);
// If there is no unvisited neighbor, remove the last visited cell from the stack
// Then, back track to process the top cell of the stack
char nextDir = infoNeighbor.first;
if (nextDir == -1)
{
stackVisitedCell.pop();
continue;
}
Cell* nextCell = infoNeighbor.second;
if ((curCell != nullptr) && (nextCell != nullptr))
{
nextCell->setVisited(true);
stackVisitedCell.push(nextCell);
if (nextDir == Cell::WALL_NORTH)
{
curCell->removeWall(Cell::WALL_NORTH);
nextCell->removeWall(Cell::WALL_SOUTH);
}
else if (nextDir == Cell::WALL_EAST)
{
curCell->removeWall(Cell::WALL_EAST);
nextCell->removeWall(Cell::WALL_WEST);
}
else if (nextDir == Cell::WALL_SOUTH)
{
curCell->removeWall(Cell::WALL_SOUTH);
nextCell->removeWall(Cell::WALL_NORTH);
}
else
{
curCell->removeWall(Cell::WALL_WEST);
nextCell->removeWall(Cell::WALL_EAST);
}
}
}
}
NEIGHBOR_INFO MazeHandling::getRandomGenNeighborDir(Cell* cell)
{
NEIGHBOR_INFO retInfo(-1, nullptr);
if (cell == nullptr)
return retInfo;
int dirNorth = cell->getRowIdx() - 1;
int dirEast = cell->getColIdx() + 1;
int dirSouth = cell->getRowIdx() + 1;
int dirWest = cell->getColIdx() - 1;
std::vector<NEIGHBOR_INFO> vectorAvaiNeightbor;
if (dirNorth >= 0)
{
Cell* cellNorth = m_arrayMazeData[static_cast<size_t>(dirNorth)][static_cast<size_t>(cell->getColIdx())];
if ( (cellNorth) && (cellNorth->isVisited() == false) )
vectorAvaiNeightbor.push_back(NEIGHBOR_INFO(Cell::WALL_NORTH, cellNorth));
}
if (dirEast < MAZE_COLS)
{
Cell* cellEast = m_arrayMazeData[static_cast<size_t>(cell->getRowIdx())][static_cast<size_t>(dirEast)];
if ( (cellEast) && (cellEast->isVisited() == false) )
vectorAvaiNeightbor.push_back(NEIGHBOR_INFO(Cell::WALL_EAST, cellEast));
}
if (dirSouth < MAZE_ROWS)
{
Cell* cellSouth = m_arrayMazeData[static_cast<size_t>(dirSouth)][static_cast<size_t>(cell->getColIdx())];
if ( (cellSouth) && (cellSouth->isVisited() == false) )
vectorAvaiNeightbor.push_back(NEIGHBOR_INFO(Cell::WALL_SOUTH, cellSouth));
}
if (dirWest >= 0)
{
Cell* cellWest = m_arrayMazeData[static_cast<size_t>(cell->getRowIdx())][static_cast<size_t>(dirWest)];
if ( (cellWest) && (cellWest->isVisited() == false) )
vectorAvaiNeightbor.push_back(NEIGHBOR_INFO(Cell::WALL_WEST, cellWest));
}
// Get a random neighbor
if (vectorAvaiNeightbor.size() > 0)
{
size_t ranAvaiNeightbor = static_cast<size_t>(rand()) % vectorAvaiNeightbor.size();
retInfo = vectorAvaiNeightbor.at(ranAvaiNeightbor);
}
return retInfo;
}
void MazeHandling::solveMazeData()
{
if (!m_bMazeDataAvailable)
return;
resetVisitedFlag();
m_bSolveDataAvailable = false;
m_pathSolvedData.clear();
m_pathTraversedData.clear();
srand(static_cast<unsigned int>(time(nullptr)));
auto t1 = std::chrono::high_resolution_clock::now();
switch (m_eSolveMazeType)
{
case SOLVEMAZE_DFS:
solveDFS();
break;
case SOLVEMAZE_BFS:
solveBFS();
break;
}
auto t2 = std::chrono::high_resolution_clock::now();
int nExecuteTime = static_cast<int>(std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count());
QObject* pParent = this->parent();
static_cast<MainWindow*>(pParent)->updateExecuteTime(nExecuteTime);
m_bSolveDataAvailable = true;
this->update();
}
void MazeHandling::solveDFS()
{
/*
Depth-First-Search( Maze m )
Mark m.StartNode "Visited"
PushStack( m.StartNode )
While Stack.NotEmpty
c <- TopStack
If c is the goal
Exit
Else
If there are unvisited available neighbors
Chose a random neighbor n of c
Mark n "Visited"
PushStack( n )
Else
PopStack(c)
End procedure
*/
if ((m_pStartCell == nullptr) || (m_pEndCell == nullptr))
return;
std::stack<Cell*> stackVisitedCell;
m_pStartCell->setVisited(true);
m_pStartCell->setParentCell(nullptr);
stackVisitedCell.push(m_pStartCell);
while ( !stackVisitedCell.empty() )
{
Cell* curCell = stackVisitedCell.top();
if ((curCell->getRowIdx() == m_pEndCell->getRowIdx()) && (curCell->getColIdx() == m_pEndCell->getColIdx()))
{
break; // End point is found, exit the loop
}
else
{
NEIGHBOR_INFO infoNeighbor = getRandomSolveNeighborDir(curCell);
char nextDir = infoNeighbor.first;
if (nextDir != -1)
{
Cell* nextCell = infoNeighbor.second;
if (nextCell != nullptr)
{
nextCell->setVisited(true);
nextCell->setParentCell(curCell);
stackVisitedCell.push(nextCell);
}
}
else
{
m_pathTraversedData.push_back(curCell);
stackVisitedCell.pop();
}
}
}
if ( !stackVisitedCell.empty() )
{
while ( !stackVisitedCell.empty() )
{
Cell* curCell = stackVisitedCell.top();
m_pathSolvedData.push_back(curCell);
stackVisitedCell.pop( );
}
}
}
void MazeHandling::solveBFS()
{
/*
Breadth-First-Search( Maze m )
Mark m.StartNode "Visited"
EnQueue( m.StartNode )
While Queue.NotEmpty
c <- DeQueue
If c is the goal
Exit
Else
Foreach unvisted neighbors n of c
Mark n "Visited"
EnQueue( n )
Mark c "Examined"
End procedure
*/
if ((m_pStartCell == nullptr) || (m_pEndCell == nullptr))
return;
std::queue<Cell*> queueVisitedCell;
std::vector<Cell*> vecExaminedCell;
m_pStartCell->setVisited(true);
m_pStartCell->setParentCell(nullptr);
queueVisitedCell.push(m_pStartCell);
while ( !queueVisitedCell.empty() )
{
// first: cell, second: it's parent
Cell* curCell = queueVisitedCell.front();
queueVisitedCell.pop();
if ((curCell->getRowIdx() == m_pEndCell->getRowIdx()) && (curCell->getColIdx() == m_pEndCell->getColIdx()))
{
vecExaminedCell.push_back(curCell);
break; // End point is found, exit the loop
}
else
{
std::vector<Cell *> listNeighborCell;
getAvailableSolveNeightbors(curCell, listNeighborCell);
for (size_t nCellIdx = 0; nCellIdx < listNeighborCell.size(); ++nCellIdx)
{
Cell* neighborCell = listNeighborCell.at(nCellIdx);
neighborCell->setVisited(true);
neighborCell->setParentCell(curCell);
queueVisitedCell.push(neighborCell);
}
vecExaminedCell.push_back(curCell);
}
}
// Because examined list is containing unexpected cells,
// now we find the path from end cell by checking availability of parent cell
size_t nExaminedCellSize = vecExaminedCell.size();
if (nExaminedCellSize > 3) // at least there are some cells except start and end cells
{
Cell* curCell = vecExaminedCell[nExaminedCellSize - 1];
m_pathSolvedData.push_back(curCell);
size_t nPreviousIndex = nExaminedCellSize - 2;
Cell* previousCell = nullptr;
while ( curCell->getParentCell() != nullptr )
{
previousCell = vecExaminedCell[nPreviousIndex];
if (previousCell == curCell->getParentCell())
{
m_pathSolvedData.push_back(previousCell);
if (previousCell->getParentCell() == nullptr)
break;
curCell = previousCell;
}
else
{
m_pathTraversedData.push_back(previousCell);
}
nPreviousIndex--;
}
}
}
NEIGHBOR_INFO MazeHandling::getRandomSolveNeighborDir(Cell* cell)
{
NEIGHBOR_INFO retInfo(-1, nullptr);
if (cell == nullptr)
return retInfo;
int dirNorth = cell->getRowIdx() - 1;
int dirEast = cell->getColIdx() + 1;
int dirSouth = cell->getRowIdx() + 1;
int dirWest = cell->getColIdx() - 1;
std::vector<NEIGHBOR_INFO> vectorAvaiNeightbor;
if ((dirNorth >= 0) && (!cell->isNorthWall()))
{
Cell* cellNorth = m_arrayMazeData[static_cast<size_t>(dirNorth)][static_cast<size_t>(cell->getColIdx())];
if ( (cellNorth) && (cellNorth->isVisited() == false) )
vectorAvaiNeightbor.push_back(NEIGHBOR_INFO(Cell::WALL_NORTH, cellNorth));
}
if ((dirEast < MAZE_COLS) && (!cell->isEastWall()))
{
Cell* cellEast = m_arrayMazeData[static_cast<size_t>(cell->getRowIdx())][static_cast<size_t>(dirEast)];
if ( (cellEast) && (cellEast->isVisited() == false) )
vectorAvaiNeightbor.push_back(NEIGHBOR_INFO(Cell::WALL_EAST, cellEast));
}
if ((dirSouth < MAZE_ROWS) &&(!cell->isSouthWall()))
{
Cell* cellSouth = m_arrayMazeData[static_cast<size_t>(dirSouth)][static_cast<size_t>(cell->getColIdx())];
if ( (cellSouth) && (cellSouth->isVisited() == false) )
vectorAvaiNeightbor.push_back(NEIGHBOR_INFO(Cell::WALL_SOUTH, cellSouth));
}
if ((dirWest >= 0) && (!cell->isWestWall()))
{
Cell* cellWest = m_arrayMazeData[static_cast<size_t>(cell->getRowIdx())][static_cast<size_t>(dirWest)];
if ( (cellWest) && (cellWest->isVisited() == false) )
vectorAvaiNeightbor.push_back(NEIGHBOR_INFO(Cell::WALL_WEST, cellWest));
}
// Get a random neighbor
if (vectorAvaiNeightbor.size() > 0)
{
size_t ranAvaiNeightbor = static_cast<size_t>(rand()) % vectorAvaiNeightbor.size();
retInfo = vectorAvaiNeightbor.at(ranAvaiNeightbor);
}
return retInfo;
}
void MazeHandling::getAvailableSolveNeightbors(Cell *cell, std::vector<Cell *> &listCell)
{
if (cell == nullptr)
return;
int dirNorth = cell->getRowIdx() - 1;
int dirEast = cell->getColIdx() + 1;
int dirSouth = cell->getRowIdx() + 1;
int dirWest = cell->getColIdx() - 1;
if ((dirNorth >= 0) && (!cell->isNorthWall()))
{
Cell* cellNorth = m_arrayMazeData[static_cast<size_t>(dirNorth)][static_cast<size_t>(cell->getColIdx())];
if ( (cellNorth) && (cellNorth->isVisited() == false) )
listCell.push_back(cellNorth);
}
if ((dirEast < MAZE_COLS) && (!cell->isEastWall()))
{
Cell* cellEast = m_arrayMazeData[static_cast<size_t>(cell->getRowIdx())][static_cast<size_t>(dirEast)];
if ( (cellEast) && (cellEast->isVisited() == false) )
listCell.push_back(cellEast);
}
if ((dirSouth < MAZE_ROWS) &&(!cell->isSouthWall()))
{
Cell* cellSouth = m_arrayMazeData[static_cast<size_t>(dirSouth)][static_cast<size_t>(cell->getColIdx())];
if ( (cellSouth) && (cellSouth->isVisited() == false) )
listCell.push_back(cellSouth);
}
if ((dirWest >= 0) && (!cell->isWestWall()))
{
Cell* cellWest = m_arrayMazeData[static_cast<size_t>(cell->getRowIdx())][static_cast<size_t>(dirWest)];
if ( (cellWest) && (cellWest->isVisited() == false) )
listCell.push_back(cellWest);
}
}
void MazeHandling::paintEvent(QPaintEvent*)
{
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
QPen myPen(Qt::black, CELL_LINE, Qt::SolidLine);
painter.setPen(myPen);
size_t nSolveDataSize = m_pathSolvedData.size();
if ((m_bSolveDataAvailable) && (nSolveDataSize > 0))
{
// Draw path from 2nd ~ (n - 1)th cell because 1st cell is starting point and (n)th is end point
for (size_t nSolveIdx = 1; nSolveIdx < nSolveDataSize - 1; ++nSolveIdx)
{
Cell* cell = m_pathSolvedData[nSolveIdx];
if (cell == nullptr)
continue;
int ptX = static_cast<int>(cell->getColIdx() * CELL_SIZE) + CELL_LINE/2;
int ptY = static_cast<int>(cell->getRowIdx() * CELL_SIZE) + CELL_LINE/2;
QPainterPath path;
path.addRect(QRectF(ptX, ptY, CELL_SIZE, CELL_SIZE));
painter.fillPath(path, Qt::green);
}
}
size_t nTraversedDataSize = m_pathTraversedData.size();
if ((m_bSolveDataAvailable) && (nTraversedDataSize > 0))
{
for (size_t nTraverseIdx = 0; nTraverseIdx < nTraversedDataSize; ++nTraverseIdx)
{
Cell* cell = m_pathTraversedData[nTraverseIdx];
if (cell == nullptr)
continue;
int ptX = static_cast<int>(cell->getColIdx() * CELL_SIZE) + CELL_LINE/2;
int ptY = static_cast<int>(cell->getRowIdx() * CELL_SIZE) + CELL_LINE/2;
QPainterPath path;
path.addRect(QRectF(ptX, ptY, CELL_SIZE, CELL_SIZE));
painter.fillPath(path, Qt::gray);
}
}
if (m_bMazeDataAvailable)
{
for (size_t nRowIndex = 0; nRowIndex < MAZE_ROWS; ++nRowIndex)
{
for (size_t nColIndex = 0; nColIndex < MAZE_COLS; ++nColIndex)
{
Cell* cell = m_arrayMazeData[nRowIndex][nColIndex];
if (cell == nullptr)
continue;
int ptX = static_cast<int>(nColIndex * CELL_SIZE) + CELL_LINE/2;
int ptY = static_cast<int>(nRowIndex * CELL_SIZE) + CELL_LINE/2;
if ((m_pStartCell) && (m_pStartCell->getRowIdx() == cell->getRowIdx())
&& (m_pStartCell->getColIdx() == cell->getColIdx()))
{
QPainterPath path;
path.addRoundedRect(QRectF(ptX + CELL_LINE/2, ptY + CELL_LINE/2, CELL_SIZE - CELL_LINE, CELL_SIZE - CELL_LINE), CELL_SIZE/2, CELL_SIZE/2);
painter.fillPath(path, Qt::blue);
}
if ((m_pEndCell) && (m_pEndCell->getRowIdx() == cell->getRowIdx())
&& (m_pEndCell->getColIdx() == cell->getColIdx()))
{
QPainterPath path;
path.addRoundedRect(QRectF(ptX + CELL_LINE/2, ptY + CELL_LINE/2, CELL_SIZE - CELL_LINE, CELL_SIZE - CELL_LINE), CELL_SIZE/2, CELL_SIZE/2);
painter.fillPath(path, Qt::red);
}
if (cell->isNorthWall())
painter.drawLine(ptX, ptY, ptX + CELL_SIZE, ptY);
if (cell->isEastWall())
painter.drawLine(ptX + CELL_SIZE, ptY, ptX + CELL_SIZE, ptY + CELL_SIZE);
if (cell->isSouthWall())
painter.drawLine(ptX, ptY + CELL_SIZE, ptX + CELL_SIZE, ptY + CELL_SIZE);
if (cell->isWestWall())
painter.drawLine(ptX, ptY, ptX, ptY + CELL_SIZE);
}
}
}
}