//7966044    vrs    3984    Accepted    376K    0MS    GCC    2108B    2010-12-04 13:38:57
//POJ 3984 第二届顶嵌杯决赛B题
//走迷宫 广搜
//要用GCC编译,没得用STL。郁闷,只能自己写个队列操作
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define bool int

 

int MAP[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
char a[10][10];

int before[10][10];
bool state[10][10];
int outputStr[30][2];
int row,col;

typedef struct _NODESTRU
{
    int col;
    int row;
    struct _NODESTRU* next;
    struct _NODESTRU* last;
}NodeStru;
NodeStru tempAll,start,end,*tempGet;

NodeStru* head,*tail,*ptrTemp;

void Init()
{
    head=0;
    tail=head;
}

void Push(NodeStru k)
{
    NodeStru *newNode=(NodeStru *)malloc(sizeof(NodeStru));
    if(head!=0)
        head->last=newNode;
    newNode->row=k.row;
    newNode->col=k.col;
    newNode->next=head;
    newNode->last=0;
    head=newNode;
    if(head->next==0)
        tail=newNode;
}

bool IsEmpty()
{
    if(head==0)
        return 1;
    return 0;
}

NodeStru* Front()
{
    return tail;
}

void Pop()
{
    NodeStru* temp;
    if(head->next==0)
    {
        temp=tail;
        head=tail=0;
    }
    else
    {
        temp=tail;
        tail=tail->last;
        tail->next=0;
    }
    free(temp);
}

void Clear()
{
    NodeStru* temp;
    while(head->next!=0)
    {
        temp=head;
        head=head->next;
        free(temp);
    }
    free(head);
    head=tail=0;
}

int bfs()
{
    int i;
    while(!IsEmpty())
    {
        tempGet=Front();   
        tempAll.row=tempGet->row;
        tempAll.col=tempGet->col;
        Pop();
        if(tempAll.row==4 && tempAll.col==4)
            return 1;
        for(i=0;i<4;i++)
        {
            col=tempAll.col+MAP[i][1];
            row=tempAll.row+MAP[i][0];

            if(row>=0 && row<5 && col>=0 && col<5 && (state[row][col]==0) &&(a[row][col]==0))
            {
                start.row=row;
                start.col=col;
                before[row][col]=i;
                Push(start);
                state[row][col]=1;
            }
        }
       
    }
    return 0;
}


int main()
{
    int i,j,k;
    int tempRow,tempCol,mapID;
    for(i=0;i<5;i++)
        for(j=0;j<5;j++)
            scanf("%d",&a[i][j]);

    memset(before,0,sizeof(before));
    memset(state,0,sizeof(state));
    Init();
    start.row=0;
    start.col=0;
    state[0][0]=1;
    Push(start);

    bfs();
    Clear();
    tempRow=4;
    tempCol=4;
    k=0;
    while(tempRow>=0 && tempCol>=0)
    {
        outputStr[k][0]=tempRow;
        outputStr[k++][1]=tempCol;
        mapID=before[tempRow][tempCol];
        tempRow-=MAP[mapID][0];
        tempCol-=MAP[mapID][1];
    }

    for(i=k-1;i>=0;i--)
        printf("(%d, %d)\n",outputStr[i][0],outputStr[i][1]);
    return 0;
}

posted on 2010-12-04 14:36  VRS  阅读(466)  评论(0编辑  收藏  举报