Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
0 / 0 / 0
Регистрация: 16.10.2020
Сообщений: 10
1

Генерация лабиринта

17.10.2022, 16:31. Показов 307. Ответов 0
Метки с++ (Все метки)

Author24 — интернет-сервис помощи студентам
Всем кодерам доброго времени суток)))
Написал код для генерации лабиринта и нахождении пути из него...Но вышел очень громоздкий..Может подскажите как можно его сократить хоть как-нибудь,оставляя структуру той же самой(использование векторов,классов и тд)?

Буду рад выслушать,а ещё лучше увидеть варианты как можно его улучшить)

C++
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
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
#include <iostream>
#include <string>
#include <random>
#include <time.h>
#include <vector>
#include <stack>
 
class CCoordinate
{
    public:
        explicit CCoordinate(int iX, int iY);
    ~CCoordinate() = default;
    bool operator==(const CCoordinate &other) const;
 
    void SetX(int iX);
    int GetX() const;
 
    void SetY(int iY);
    int GetY() const;
 
    private:
        int m_iX;
    int m_iY;
};
 
CCoordinate::CCoordinate(int iX, int iY): m_iX(iX), m_iY(iY) {}
 
bool CCoordinate::operator==(const CCoordinate &other) const
{
    return (m_iX == other.GetX()) && (m_iY == other.GetY());
}
 
void CCoordinate::SetX(int iX)
{
    m_iX = iX;
}
 
int CCoordinate::GetX() const
{
    return m_iX;
}
 
void CCoordinate::SetY(int iY)
{
    m_iY = iY;
}
 
int CCoordinate::GetY() const
{
    return m_iY;
}
 
class CCell
{
    public:
        explicit CCell();
    ~CCell() = default;
 
    void SetTopWall(bool bTopWall);
    bool GetTopWall() const;
 
    void SetLeftWall(bool bLeftWall);
    bool GetLeftWall() const;
 
    void SetRightWall(bool bRightWall);
    bool GetRightWall() const;
 
    void SetBottomWall(bool bBottomWall);
    bool GetBottomWall() const;
 
    void SetVisited(bool bVisited);
    bool GetVisited() const;
 
    void SetCoordinate(const CCoordinate &position);
    const CCoordinate &GetCoordinate() const;
 
    private:
        bool m_bTopWall;
    bool m_bLeftWall;
    bool m_bRightWall;
    bool m_bBottomWall;
    bool m_bVisited;
    CCoordinate m_position;
};
 
CCell::CCell(): m_bTopWall(true), m_bLeftWall(true), m_bRightWall(true), m_bBottomWall(true), m_bVisited(false), m_position(CCoordinate(-1, -1)) {}
 
void CCell::SetTopWall(bool bTopWall)
{
    m_bTopWall = bTopWall;
}
 
bool CCell::GetTopWall() const
{
    return m_bTopWall;
}
 
void CCell::SetLeftWall(bool bLeftWall)
{
    m_bLeftWall = bLeftWall;
}
 
bool CCell::GetLeftWall() const
{
    return m_bLeftWall;
}
 
void CCell::SetRightWall(bool bRightWall)
{
    m_bRightWall = bRightWall;
}
 
bool CCell::GetRightWall() const
{
    return m_bRightWall;
}
 
void CCell::SetBottomWall(bool bBottomWall)
{
    m_bBottomWall = bBottomWall;
}
 
bool CCell::GetBottomWall() const
{
    return m_bBottomWall;
}
 
void CCell::SetVisited(bool bVisited)
{
    m_bVisited = bVisited;
}
 
bool CCell::GetVisited() const
{
    return m_bVisited;
}
 
void CCell::SetCoordinate(const CCoordinate &position)
{
    m_position = position;
}
 
const CCoordinate &CCell::GetCoordinate() const
{
    return m_position;
}
 
enum class EDirection
{
    ED_UNKNOWN = 0,
        ED_UP = 1,
        ED_LEFT = 2,
        ED_RIGHT = 3,
        ED_DOWN = 4
};
 
class CMaze
{
    public:
        explicit CMaze(int iRows, int iColumns, int iSeed = 0, bool bUseSeed = false);
    ~CMaze() = default;
 
    std::vector<std::vector < CCell>> &GetMaze();
    const std::vector<std::vector < CCell>> &GetMaze() const;
    int GetRows() const;
    int GetColumns() const;
    std::vector<CCoordinate> GetUnvisitedNeighbours(const CCoordinate &position);
 
    private:
        void GenerateMaze(int iSeed, bool bUseSeed);
    void AllocateCapacity();
    void InitializePositionCoordinates();
    void GenerateMazeRecursive(CCell &currentCell, int &iVisitedCells, bool bStackPopped = false);
    bool AdjacentCellsVisited(const CCoordinate &position) const;
    void TidyVisitedCells();
 
    bool CanGoUp(int iY) const;
    bool CanGoLeft(int iX) const;
    bool CanGoRight(int iX) const;
    bool CanGoDown(int iY) const;
 
    EDirection GetAcceptableDirection(const CCoordinate &position) const;
 
    private:
        std::vector<std::vector < CCell>> m_vMaze;
    std::stack<CCell> m_sStackTrace;
    int m_iMazeSize;
    int m_iRows;
    int m_iColumns;
    EDirection m_eLastDirection;
};
 
CMaze::CMaze(int iRows, int iColumns, int iSeed, bool bUseSeed): m_iRows(iRows), m_iColumns(iColumns), m_iMazeSize(iRows *iColumns), m_eLastDirection(EDirection::ED_UNKNOWN)
{
    GenerateMaze(iSeed, bUseSeed);
}
 
std::vector<std::vector < CCell>> &CMaze::GetMaze()
{
    return m_vMaze;
}
 
const std::vector<std::vector < CCell>> &CMaze::GetMaze() const
{
    return m_vMaze;
}
 
int CMaze::GetRows() const
{
    return m_iRows;
}
 
int CMaze::GetColumns() const
{
    return m_iColumns;
}
 
std::vector<CCoordinate> CMaze::GetUnvisitedNeighbours(const CCoordinate &position)
{
    std::vector<CCoordinate> vNeighbours;
 
    int iY = position.GetY();
    int iX = position.GetX();
 
    if (CanGoUp(iY) &&
        m_vMaze[iY - 1][iX].GetVisited() == false)
    {
        vNeighbours.push_back(m_vMaze[iY - 1][iX].GetCoordinate());
    }
 
    if (CanGoLeft(iX) &&
        m_vMaze[iY][iX - 1].GetVisited() == false)
    {
        vNeighbours.push_back(m_vMaze[iY][iX - 1].GetCoordinate());
    }
 
    if (CanGoRight(iX) &&
        m_vMaze[iY][iX + 1].GetVisited() == false)
    {
        vNeighbours.push_back(m_vMaze[iY][iX + 1].GetCoordinate());
    }
 
    if (CanGoDown(iY) &&
        m_vMaze[iY + 1][iX].GetVisited() == false)
    {
        vNeighbours.push_back(m_vMaze[iY + 1][iX].GetCoordinate());
    }
 
    return vNeighbours;
}
 
void CMaze::GenerateMaze(int iSeed, bool bUseSeed)
{
    bUseSeed ? srand(iSeed) : srand(time(NULL));
    AllocateCapacity();
    InitializePositionCoordinates();
 
    int iVisitedCells = 0;
    GenerateMazeRecursive(m_vMaze[0][0], iVisitedCells);
    TidyVisitedCells();
}
 
void CMaze::AllocateCapacity()
{
    m_vMaze.resize(m_iRows);
    for (int i = 0; i < m_iRows; ++i)
    {
        m_vMaze[i].resize(m_iColumns);
    }
}
 
void CMaze::InitializePositionCoordinates()
{
    for (int i = 0; i < m_iRows; ++i)
    {
        for (int j = 0; j < m_iColumns; ++j)
        {
            m_vMaze[i][j].SetCoordinate(CCoordinate(j, i));
        }
    }
}
 
void CMaze::GenerateMazeRecursive(CCell &currentCell, int &iVisitedCells, bool bStackPopped)
{
    currentCell.SetVisited(true);
    if (bStackPopped == false)
    {
        ++iVisitedCells;
        switch (m_eLastDirection)
        {
            case EDirection::ED_UP:
                {
                    currentCell.SetBottomWall(false);
                }
 
                break;
            case EDirection::ED_LEFT:
                {
                    currentCell.SetRightWall(false);
                }
 
                break;
            case EDirection::ED_RIGHT:
                {
                    currentCell.SetLeftWall(false);
                }
 
                break;
            case EDirection::ED_DOWN:
                {
                    currentCell.SetTopWall(false);
                }
 
                break;
        }
    }
 
    if (iVisitedCells == m_iMazeSize)
    {
        const CCoordinate &lastCoordinate = currentCell.GetCoordinate();
        std::vector<CCoordinate> vLastCell = GetUnvisitedNeighbours(lastCoordinate);
        bool bUseLastCoordinate = vLastCell.size() > 0;
        switch (bUseLastCoordinate ? GetAcceptableDirection(lastCoordinate) : EDirection::ED_UNKNOWN)
        {
            case EDirection::ED_UP:
                {
                    currentCell.SetTopWall(false);
                    m_vMaze[lastCoordinate.GetY() - 1][lastCoordinate.GetX()].SetBottomWall(false);
                }
 
                break;
            case EDirection::ED_LEFT:
                {
                    currentCell.SetLeftWall(false);
                    m_vMaze[lastCoordinate.GetY()][lastCoordinate.GetX() - 1].SetRightWall(false);
                }
 
                break;
            case EDirection::ED_RIGHT:
                {
                    currentCell.SetRightWall(false);
                    m_vMaze[lastCoordinate.GetY()][lastCoordinate.GetX() + 1].SetLeftWall(false);
                }
 
                break;
            case EDirection::ED_DOWN:
                {
                    currentCell.SetBottomWall(false);
                    m_vMaze[lastCoordinate.GetY() + 1][lastCoordinate.GetX()].SetTopWall(false);
                }
 
                break;
        }
 
        return;
    }
 
    m_sStackTrace.push(currentCell);
 
    const CCoordinate &currentPosition = currentCell.GetCoordinate();
    if (currentCell.GetVisited() && AdjacentCellsVisited(currentPosition))
    {
        while (AdjacentCellsVisited(m_sStackTrace.top().GetCoordinate()))
        {
            m_sStackTrace.pop();
        }
 
        const CCoordinate &newPosition = m_sStackTrace.top().GetCoordinate();
        GenerateMazeRecursive(m_vMaze[newPosition.GetY()][newPosition.GetX()], iVisitedCells, true);
        return;
    }
 
    EDirection eRandomDirection = GetAcceptableDirection(currentPosition);
    m_eLastDirection = eRandomDirection;
 
    switch (eRandomDirection)
    {
        case EDirection::ED_UP:
            {
                currentCell.SetTopWall(false);
                CCell &nextCell = m_vMaze[currentPosition.GetY() - 1][currentPosition.GetX()];
                GenerateMazeRecursive(nextCell, iVisitedCells);
            }
 
            break;
        case EDirection::ED_LEFT:
            {
                currentCell.SetLeftWall(false);
                CCell &nextCell = m_vMaze[currentPosition.GetY()][currentPosition.GetX() - 1];
                GenerateMazeRecursive(nextCell, iVisitedCells);
            }
 
            break;
        case EDirection::ED_RIGHT:
            {
                currentCell.SetRightWall(false);
                CCell &nextCell = m_vMaze[currentPosition.GetY()][currentPosition.GetX() + 1];
                GenerateMazeRecursive(nextCell, iVisitedCells);
            }
 
            break;
        case EDirection::ED_DOWN:
            {
                currentCell.SetBottomWall(false);
                CCell &nextCell = m_vMaze[currentPosition.GetY() + 1][currentPosition.GetX()];
                GenerateMazeRecursive(nextCell, iVisitedCells);
            }
 
            break;
    }
}
 
bool CMaze::AdjacentCellsVisited(const CCoordinate &position) const
{
    int iCurrentX = position.GetX();
    int iCurrentY = position.GetY();
 
    if ((CanGoUp(iCurrentY) && m_vMaze[iCurrentY - 1][iCurrentX].GetVisited() == false) ||
        (CanGoLeft(iCurrentX) && m_vMaze[iCurrentY][iCurrentX - 1].GetVisited() == false) ||
        (CanGoRight(iCurrentX) && m_vMaze[iCurrentY][iCurrentX + 1].GetVisited() == false) ||
        (CanGoDown(iCurrentY) && m_vMaze[iCurrentY + 1][iCurrentX].GetVisited() == false))
    {
        return false;
    }
 
    return true;
}
 
void CMaze::TidyVisitedCells()
{
    for (int i = 0; i < m_iRows; ++i)
    {
        for (int j = 0; j < m_iColumns; ++j)
        {
            m_vMaze[i][j].SetVisited(false);
        }
    }
}
 
bool CMaze::CanGoUp(int iY) const
{
    return iY > 0;
}
 
bool CMaze::CanGoLeft(int iX) const
{
    return iX > 0;
}
 
bool CMaze::CanGoRight(int iX) const
{
    return iX < (m_iColumns - 1);
}
 
bool CMaze::CanGoDown(int iY) const
{
    return iY < (m_iRows - 1);
}
 
EDirection CMaze::GetAcceptableDirection(const CCoordinate &position) const
{
    EDirection eRandomDirection = EDirection::ED_UNKNOWN;
 
    while (true)
    {
        eRandomDirection = static_cast<EDirection> ((rand() % 4) + 1);
 
        if (eRandomDirection == EDirection::ED_UP && CanGoUp(position.GetY()) && m_vMaze[position.GetY() - 1][position.GetX()].GetVisited() == false ||
            eRandomDirection == EDirection::ED_LEFT && CanGoLeft(position.GetX()) && m_vMaze[position.GetY()][position.GetX() - 1].GetVisited() == false ||
            eRandomDirection == EDirection::ED_RIGHT && CanGoRight(position.GetX()) && m_vMaze[position.GetY()][position.GetX() + 1].GetVisited() == false ||
            eRandomDirection == EDirection::ED_DOWN && CanGoDown(position.GetY()) && m_vMaze[position.GetY() + 1][position.GetX()].GetVisited() == false)
        {
            break;
        }
    }
 
    return eRandomDirection;
}
 
EDirection GetDirection(const CCoordinate &from, const CCoordinate &to)
{
    if (from.GetX() > to.GetX())
    {
        return EDirection::ED_LEFT;
    }
 
    if (from.GetX() < to.GetX())
    {
        return EDirection::ED_RIGHT;
    }
 
    if (from.GetY() > to.GetY())
    {
        return EDirection::ED_UP;
    }
 
    if (from.GetY() < to.GetY())
    {
        return EDirection::ED_DOWN;
    }
 
    return EDirection::ED_UNKNOWN;
}
 
bool findPath(CMaze &maze, const CCoordinate &from, const CCoordinate &to)
{
    std::vector<std::vector < CCell>> &vMaze = maze.GetMaze();
    vMaze[from.GetY()][from.GetX()].SetVisited(true);
 
    if (from == to)
    {
        return true;
    }
 
    std::vector<CCoordinate> vNeighbours = maze.GetUnvisitedNeighbours(from);
    int iSize = vNeighbours.size();
    for (int i = 0; i < iSize; ++i)
    {
        const CCoordinate &neighbour = vNeighbours[i];
        CCell &neighbourCell = vMaze[neighbour.GetY()][neighbour.GetX()];
        EDirection direction = GetDirection(from, neighbour);
        bool bIsWallObstructing = false;
 
        switch (direction)
        {
            case EDirection::ED_UP:
                {
                    bIsWallObstructing = neighbourCell.GetBottomWall();
                }
 
                break;
            case EDirection::ED_LEFT:
                {
                    bIsWallObstructing = neighbourCell.GetRightWall();
                }
 
                break;
            case EDirection::ED_RIGHT:
                {
                    bIsWallObstructing = neighbourCell.GetLeftWall();
                }
 
                break;
            case EDirection::ED_DOWN:
                {
                    bIsWallObstructing = neighbourCell.GetTopWall();
                }
 
                break;
        }
 
        if (neighbourCell.GetVisited() == false && bIsWallObstructing == false)
        {
            if (findPath(maze, neighbour, to))
            {
                return true;
            }
        }
    }
 
    vMaze[from.GetY()][from.GetX()].SetVisited(false);
    return false;
}
 
void PrintMaze(const CMaze &maze)
{
    const std::vector<std::vector < CCell>> &vMaze = maze.GetMaze();
 
    std::string sFirstThirdRow = "";
    std::string sSecondThirdRow = "";
    std::string sThirdThirdRow = "";
    bool bFirstThirdPrintedOnce = false;
 
    int iRows = maze.GetRows();
    int iColumns = maze.GetColumns();
 
    for (int i = 0; i < iRows; ++i)
    {
        for (int j = 0; j < iColumns; ++j)
        {
            const CCell &cell = vMaze[i][j];
            if (j == 0)
            {
                sFirstThirdRow += "+";
            }
 
            cell.GetTopWall() ? sFirstThirdRow += "---" : sFirstThirdRow += "   ";
            sFirstThirdRow += "+";
 
            if (j == 0)
            {
                cell.GetLeftWall() ? sSecondThirdRow += "|" : sSecondThirdRow += " ";
            }
 
            cell.GetVisited() ? sSecondThirdRow += " . " : sSecondThirdRow += "   ";
            cell.GetRightWall() ? sSecondThirdRow += "|" : sSecondThirdRow += " ";
 
            if (j == 0)
            {
                sThirdThirdRow += "+";
            }
 
            cell.GetBottomWall() ? sThirdThirdRow += "---" : sThirdThirdRow += "   ";
            sThirdThirdRow += "+";
        }
 
        if (bFirstThirdPrintedOnce == false)
        {
            std::cout << sFirstThirdRow << std::endl;
            bFirstThirdPrintedOnce = true;
        }
 
        std::cout << sSecondThirdRow << std::endl;
        std::cout << sThirdThirdRow << std::endl;
 
        sFirstThirdRow = "";
        sSecondThirdRow = "";
        sThirdThirdRow = "";
    }
}
 
int main(int argc, char **argv)
{
    int iRows = 0;
    int iColumns = 0;
    int iSeed = 0;
    bool bUseSeed = false;
 
    switch (argc)
    {
        case 0:
        case 1:
        case 2:
            {
                return -1;
            }
 
        case 3:
            {
                iRows = std::atoi(argv[1]);
                iColumns = std::atoi(argv[2]);
            }
 
            break;
        case 4:
            {
                iRows = std::atoi(argv[1]);
                iColumns = std::atoi(argv[2]);
                iSeed = std::atoi(argv[3]);
                bUseSeed = true;
            }
    }
 
    CMaze maze(iRows, iColumns, iSeed, bUseSeed);
    findPath(maze, CCoordinate(0, 0), CCoordinate(iColumns - 1, iRows - 1));
    PrintMaze(maze);
 
    return 0;
}
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
17.10.2022, 16:31
Ответы с готовыми решениями:

Генерация лабиринта
Разработать приложение, генерирующее лабиринт размером m x n клеток. Дополнительные условия: ...

Генерация лабиринта
Добрый вечер! Подскажите, как решить ошибку (Вызвано исключение по адресу 0x00271DF4 в...

Генерация 6 свободного лабиринта
#include &quot;stdio.h&quot; #include &quot;stdlib.h&quot; #include &quot;time.h&quot; int ShowMaze(int size, int**maze) { ...

Генерация случайного лабиринта
Вообщем требуется сгенерировать лабиринт 12х12 с одним входом и выходом. Лабиринт представляется...

Прохождение лабиринта
Имеется лабиринт. Нужно составить алгоритм, по которому программа найдет выход из лабиринта. мой...

0
17.10.2022, 16:31
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
17.10.2022, 16:31
Помогаю со студенческими работами здесь

Прохождение лабиринта
Как написать программу для прохождения лабиринта? У меня не получается. Саму программу можно не...

Обход лабиринта
Стал делать задачу из книги Дейтлов про лабиринт, и наткнулся на некоторую проблему. Текст...

Обход лабиринта
Добрый вечер. Стоит задача обойти лабиринт, заданный матрицей (вводятся размерности и начальное...

Выход из лабиринта
нужно использовать правило правой руки (и по диагонали тоже)

Прохождение лабиринта
Всем привет! Преподаватель по ОАиП дал задание. Учусь на специальность не связанную с...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
1
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru