|
发表于 2017-4-28 17:46:48
|
显示全部楼层
本想练练手的,结果第一道题就折腾了一下午加小半个晚上。
[mw_shl_code=c,true]#include<stdio.h>
int w,h;
char**arr;
int start_x,start_y;
char start_drt;
struct data
{
short north;//记录该单元格是否往北走过,下同
short east;
short south;
short west;
};
struct data**d;
void Initialize(int _w,int _h)
{
int i,j;
arr=(char**)malloc(sizeof(char*)*_h);
d=(struct data**)malloc(sizeof(struct data*)*_h);
for(i=0;i<_h;i++)
{
arr=(char*)malloc(sizeof(char)*_w);
d=(struct data*)malloc(sizeof(struct data)*_w);
}
for(i=0;i<_h;i++)
{
for(j=0;j<_w;j++)
{
arr[j]=getch();
printf("%c",arr[j]);
if(arr[j]=='U'||arr[j]=='D'||arr[j]=='L'||arr[j]=='R')
{
start_x=j;start_y=i;start_drt=arr[j];
}
d[j].north=d[j].east=d[j].south=d[j].west=0;
}
printf("\n");
}
}
void Free(int _h)
{
int i;
for(i=0;i<_h;i++)
free(arr);
free(arr);
}
int Scan(int y,int x,char drt)
{
int covered=0;
int determined=0;
while(1)
{
determined=0;//判断离开当前位置的去向是否确定
while(!determined)
{
switch(drt)
{
case 'U':
if(y==0||arr[y-1][x]=='*')
drt='R';
else
{
if(d[y][x].north) return covered;//返回走过的坐标数
else
{
covered+=(d[y][x].north==0&&
d[y][x].east==0&&d[y][x].south==0&&
d[y][x].west==0);//足迹累加
d[y][x].north=1;y--;
determined=1;
}
}
break;
case 'R':
if(x==w-1||arr[y][x+1]=='*')
drt='D';
else
{
if(d[y][x].east) return covered;//返回走过的坐标数
else
{
covered+=(d[y][x].north==0&&
d[y][x].east==0&&d[y][x].south==0&&
d[y][x].west==0);
d[y][x].east=1;x++;
determined=1;
}
}
break;
case 'D':
if(y==h-1||arr[y+1][x]=='*')
drt='L';
else
{
if(d[y][x].south) return covered;//返回走过的坐标数
else
{
covered+=(d[y][x].north==0&&
d[y][x].east==0&&d[y][x].south==0&&
d[y][x].west==0);
d[y][x].south=1;y++;
determined=1;
}
}
break;
case 'L':
if(x==0||arr[y][x-1]=='*')
drt='U';
else
{
if(d[y][x].west) return covered;//返回走过的坐标数
else
{
covered+=(d[y][x].north==0&&
d[y][x].east==0&&d[y][x].south==0&&
d[y][x].west==0);
d[y][x].west=1;x--;
determined=1;
}
}
break;
}
}
}
}
int main()
{
int answer;
printf("请输入行数,列数(空格隔开):");
scanf("%d %d",&h,&w);
Initialize(w,h);
answer=Scan(start_y,start_x,start_drt);
printf("走过的位置数:%d\n",answer);
Free(h);
return 0;
}[/mw_shl_code] |
|