读书人

功课代码合辑

发布时间: 2012-09-02 21:00:34 作者: rapoo

作业代码合辑

小狗走迷宫:

#include<iostream>#include<time.h>#include<stdlib.h>using namespace std;#define N 20typedef struct node{    int x,y,pre;} node;bool check(bool maze[][N],const int x,const int y){    if(x>-1&&x<N&&y>-1&&y<N&&!maze[x][y])        return true;    return false;}void printPath(node path[],size_t index){    if(path[index].pre)        printPath(path,path[index].pre);    cout<<"["<<path[index].x+1<<","<<path[index].y+1<<"]";}void traceMaze(bool maze[][N],node path[],size_t index){    static const int dir[4][2]= {{1,0},{0,1},{-1,0},{0,-1}};    if(path[index].x==N-1&&path[index].y==N-1)    {        printPath(path,index);        cout<<endl;        exit(0);    }    for(int i=0; i<4; i++)    {        int x=path[index].x+dir[i][0];        int y=path[index].y+dir[i][1];        int pre=index;        if(check(maze,x,y))        {            path[++index].x=x;            path[index].y=y;            path[index].pre=pre;            maze[x][y]=true;            traceMaze(maze,path,index);            maze[x][y]=false;        }    }}int main(){    srand(time(NULL));    bool maze[N][N]= {{0}};    node path[N*N];    int wallNum=rand()%(N);    for(int i=0; i<wallNum; i++)    {        int x=rand()%N;        int y=rand()%N;        if((x==0&&y==0)||(x==N-1&&y==N-1)||maze[x][y])        {            i--;            continue;        }        maze[x][y]=true;    }    for(int i=0; i<N; i++)    {        for(int j=0; j<N; j++)        {            cout<<maze[i][j]<<" ";        }        cout<<endl;    }    path[1].x=0,path[1].y=0,path[1].pre=0;    traceMaze(maze,path,1);}



读书人网 >编程

热点推荐