https://oshiete.goo.ne.jp/qa/9171406.html
内容はこちらと同じですが、必要とする内容は自ら考えました。
以下がそのコードとなります。
実行すると、無限ループあるいはコアダンプが出ます。
まれに出力されますが正しく"・"が表示されません。
何回かデバッグをしましたが、どうしてかわかりません。
よろしくお願いします。デバッグ多いです。
#include "a.h"
#include<stdio.h>
struct player
{
int y; //y座標
int x; //x座標
};
struct player dir(int maze[H][W],struct player p);
void solve_maze(int maze[H][W])
{
int x,y;
struct player p;
//スタート地点を見つける
for(y=0;y<H;y++)
{
for(x=0;x<W;x++)
{
if(maze[y][x] == START)
{
printf("[%d][%d]\n",y,x);
//上
if(y == 0 && maze[y][x+1] == WALL && maze[y][x-1] == WALL )
{
p.y = y+1;
p.x = x;
}
//左
else if(x == 0 && maze[y+1][x] == WALL && maze[y-1][x] == WALL )
{
p.x = x+1;
p.y = y;
}
//下
else if(y == H-1 && maze[y][x+1] == WALL && maze[y][x-1] == WALL)
{
p.y = y-1;
p.x = x;
}
//右
else if(x == W-1 && maze[y+1][x] == WALL && maze[y-1][x] == WALL )
{
p.x = x-1;
p.y = y;
}
}
}
}
do
{
p = dir(maze,p);
}
while(maze[p.y][p.x] != GOAL);
}
struct player dir(int maze[H][W],struct player p)
{
int flg = 0;
while(maze[p.y+1][p.x] == WALL && maze[p.y][p.x+1] != WALL && flg == 0)
{
//printf("a\n");
p.x = p.x+1;
maze[p.y][p.x] = TRACK;
}
if(maze[p.y+1][p.x] != WALL && flg == 0)
{
//printf("d\n");
maze[p.y][p.x] = TRACK;
p.y = p.y+1;
flg = 1;
}
while(maze[p.y][p.x+1] == WALL && maze[p.y-1][p.x] != WALL && flg == 0)
{
//printf("b\n");
p.y = p.y-1;
maze[p.y][p.x] = TRACK;
}
if(maze[p.y][p.x+1] != WALL && flg == 0)
{
//printf("c\n");
maze[p.y][p.x] = TRACK;
p.x = p.x+1;
flg = 1;
}
while(maze[p.y-1][p.x] == WALL && maze[p.y][p.x-1] != WALL && flg == 0)
{
//printf("c\n");
p.x = p.x-1;
maze[p.y][p.x] = TRACK;
}
if(maze[p.y-1][p.x] != WALL && flg == 0)
{
//printf("b\n");
maze[p.y][p.x] = TRACK;
p.y = p.y-1;
flg = 1;
}
while(maze[p.y][p.x-1] == WALL && maze[p.y+1][p.x] != WALL && flg == 0)
{
//printf("d\n");
p.y = p.y+1;
maze[p.y][p.x] = TRACK;
}
if(maze[p.y][p.x-1] != WALL && flg == 0)
{
//printf("a\n");
maze[p.y][p.x] = TRACK;
p.x = p.x-1;
flg = 1;
}
return p;
}