简单搜索题,由于很久没写搜索题的缘故,我自己的模板出现了小问题。

注意:1、如果maze[q.x][q.y] == 4的话可能会出现死循环,所以要走过之后直接标记为0。

CODE:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <queue>
using namespace std;

const int SIZE = 110;
int maze[SIZE][SIZE];
const int move[4][2] = {{10}, {-10}, {0, -1}, {01}};
int flag[SIZE][SIZE];
int N, M;
int bx, by;


struct node
{
    int x, y;
    int step;
    int costT;
}p, q;


int check(int r, int c)
{
    if(maze[r][c] != 0 && r < N && c < M && r >= 0 && c >= 0)
        return 1;
    return 0;
}


void bfs(int bx, int by)
{
    queue<node> Q;
    p.x = bx; p.y = by;
    p.step = 6; p.costT = 0;
    Q.push(p);
    while(!Q.empty())
    {
        p = Q.front();
        Q.pop();
        for(int i = 0; i < 4; i++)
        {
            q = p;
            q.x += move[i][0];
            q.y += move[i][1];
            if(check(q.x, q.y))
            {
                if(maze[q.x][q.y] == 1)
                {
                    q.step--;
                    if(q.step > 0)
                    {
                        q.costT++;
                        Q.push(q);
                    }
                }
                if(maze[q.x][q.y] == 4)
                {
                    q.step--;
                    if(q.step > 0)
                    {
                        q.costT++;
                        q.step = 6;
                        Q.push(q);
                    }
                    maze[q.x][q.y] = 0;    //可能会有死循环 
                }
                if(maze[q.x][q.y] == 3 && q.step > 1)
                {
                    printf("%d\n", ++q.costT);
                    return ;
                }
            }
        }
    }
    printf("-1\n");
    return ;
}


int main()
{
    int T;
    int i, j;
    scanf("%d", &T);
    while(T--)
    {
        memset(maze, 0sizeof(maze));
        scanf("%d%d", &N, &M);
        for(i = 0; i < N; i++)
        {
            for(j = 0; j < M; j++)
            {
                scanf("%d", &maze[i][j]);
                if(maze[i][j] == 2)
                {
                    bx = i;
                    by = j;
                }
            }
        }
        bfs(bx, by);
    }
    return 0;

} 

posted on 2012-08-19 12:02  有间博客  阅读(199)  评论(0编辑  收藏  举报