map上で、プレイヤーの位置からゴールの位置までの道のりを探索するアルゴリズムを書いてみたのですが、プログラムを実行中に強制終了してしまいます。
どこでエラーになっているのか、どうすれば直るのかお教えください。
Cpp
1#include <iostream> 2using namespace std; 3 4constexpr int MAP_SIZE = 5; // マップの縦横のサイズ 5 6// mapを描画 7void display(const int map[MAP_SIZE][MAP_SIZE]) { 8 for (int y = 0; y < MAP_SIZE; y++) { 9 for (int x = 0; x < MAP_SIZE; x++) { 10 switch (map[y][x]) { 11 case 0: cout << "_"; break; 12 case 1: cout << "■"; break; 13 case 2: cout << "me"; break; 14 case 3: cout << "◆"; break; 15 } 16 } 17 cout << endl; 18 } 19} 20 21// その場所が通過できる場所か 22bool passMap(const int map[MAP_SIZE][MAP_SIZE], const int x, const int y) { 23 if (0 <= x && x < MAP_SIZE && 0 <= y && y < MAP_SIZE) { 24 switch (map[y][x]) { 25 case 1: return false; break; // ■のみ通過不可 26 default: return true; break; 27 } 28 } 29 return false; 30} 31 32// 問題のアルゴリズム 33// ゴールまでの道のりを探索する 幅優先探索 34bool searchRoute(const int map[MAP_SIZE][MAP_SIZE], int route[MAP_SIZE][MAP_SIZE], int sx, int sy, int gx, int gy) { 35 if (!passMap(map, sx, sy)) return false; 36 route[sy][sx] = 1; 37 if (sx == gx && sy == gy) return true; 38 if (searchRoute(map, route, sx, sy-1, gx, gy)) return true; 39 if (searchRoute(map, route, sx, sy+1, gx, gy)) return true; 40 if (searchRoute(map, route, sx-1, sy, gx, gy)) return true; 41 if (searchRoute(map, route, sx+1, sy, gx, gy)) return true; 42 route[sy][sx] = 0; 43 return false; 44} 45 46int main() { 47 // 0:道 1:壁 2:自分 3:ゴール 48 int map[MAP_SIZE][MAP_SIZE] = { 49 {0, 2, 0, 0, 0}, 50 {0, 0, 1, 0, 0}, 51 {0, 1, 0, 0, 0}, 52 {0, 0, 0, 1, 0}, 53 {0, 0, 1, 3, 0} 54 }; 55 56 display(map); 57 int route[MAP_SIZE][MAP_SIZE]; // 道のりを保存する配列 58 for (int i = 0; i < MAP_SIZE; i++) { 59 for (int j = 0; j < MAP_SIZE; j++) 60 route[i][j] = 0; 61 } 62 searchRoute(map, route, 1, 0, 3, 4); 63 cout << endl; 64 display(route); 65 66 return 0; 67}
回答3件
あなたの回答
tips
プレビュー