C++でatcoderの幅優先探索の問題に挑戦しているのですが、メモリ確保ができていないようです。
メモリ確保についてはまだまだ理解できていないので以下のエラーをなくす方法を教えて頂けたら幸いです。
エラーメッセージ
terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc
ソースコード
#include <iostream> #include <queue> using namespace std; typedef struct{ int y, x, dist; }node, node_p; char c[60][60]; int dist[60][60]; int main(){ int R, C; int sy, sx, gy, gx; cin >> R >> C >> sy >> sx >> gy >> gx; queue<node> que; for(int i = 1; i < R+1; i++){ for(int j = 1; j < C+1; j++){ cin >> c[i][j]; dist[i][j] = -1;//未訪問 } } node temp, ntemp; dist[sy][sx] = 0; temp = {sy, sx, dist[sy][sx]}; que.push(temp); //BFS while(!que.empty()){ temp = que.front(); que.pop(); //cout << temp.y << temp.x << temp.dist << endl; if(temp.y==gy && temp.x == gx){ cout << temp.dist << endl; break; } //tempから行ける頂点探す if(c[temp.y+1][temp.x] == '.' && dist[temp.y+1][temp.x] == -1){ ntemp = {temp.y+1, temp.x, temp.dist+1}; que.push(ntemp); } if(c[temp.y-1][temp.x] == '.' && dist[temp.y-1][temp.x] == -1){ ntemp = {temp.y-1, temp.x, temp.dist+1}; que.push(ntemp); } if(c[temp.y][temp.x+1] == '.' && dist[temp.y][temp.x+1] == -1){ ntemp = {temp.y, temp.x+1, temp.dist+1}; que.push(ntemp); } if(c[temp.y][temp.x-1] == '.' && dist[temp.y][temp.x-1] == -1){ ntemp = {temp.y, temp.x-1, temp.dist+1}; que.push(ntemp); } } }### ヘディングのテキスト
質問を編集して、問題へのリンクを載せてください。
ソースコードだけ見せられても、どのような入力が想定されているのか分からないので回答できません。
今回はこちらで問題へのリンクを載せておきます。次回からは最初から載せるようにしてください。問題が違うようであれば、正しいリンクを載せてください。
ABC007 C - 幅優先探索
https://atcoder.jp/contests/abc007/tasks/abc007_3
さて、bad_allocですが、メモリの確保に失敗した際に投げられる例外です。
今回のコードで、メモリの確保をしているのは、queue<node>だけです。
こちらのキューに限界を超えて要素を追加しようとしたため、bad_allocが発生しています。
なぜそのような状況に陥っているのか、調べてみてください。

回答1件
あなたの回答
tips
プレビュー