COJ 1259: 跳跳

BFS,直接入队即可。

# include <cstdio>
# include <queue>
# include <cstring>

using namespace std;

# define N 100 + 5

int n;
char g[N][N];
char vis[N][N];

struct pos{int x, y, d;};

pos st;
queue <pos> Qst[10];

const int dx[] = {0,0,1,-1};
const int dy[] = {1,-1,0,0};

int bfs(void)
{
    queue <pos> Q;
    Q.push(st);
    vis[st.x][st.y] = 1;
    while (!Q.empty())
    {
        pos cur = Q.front(); Q.pop();
        for (int i = 0; i < 4; ++i)
        {
            pos nst;
            nst.x = cur.x + dx[i];
            nst.y = cur.y + dy[i];
            if (1<=nst.x&&nst.x<=n && 1<=nst.y&&nst.y<=n && !vis[nst.x][nst.y])
            {
                vis[nst.x][nst.y] = 1;
                char ch = g[nst.x][nst.y];
                if (ch == 'E') return cur.d+1;
                if (ch == '1') continue;
                if (ch == '0') nst.d=cur.d+1, Q.push(nst);
                else if ('2'<=ch&&ch<='9')
                {
                    pos nnst;
                    while (!Qst[ch-'0'].empty())
                    {
                        nnst = Qst[ch-'0'].front(); Qst[ch-'0'].pop();
                        vis[nnst.x][nnst.y] = 1;
                        nnst.d = cur.d + 1;
                        Q.push(nnst);
                    }
                }
            }
        }
    }
    return -1;
}

void read(void)
{
    pos tmp;
    for (int i = 2; i <= 9; ++i)
    {
        while (!Qst[i].empty()) Qst[i].pop();
    }
    for (int i = 1; i <= n; ++i)
    {
        scanf("%s", g[i]+1);
        memset(vis[i]+1, 0, sizeof(char)*n);
        for (int j = 1; j <= n; ++j)
        {
            char ch = g[i][j];
            if ('2'<=ch&&ch<='9')
            {
                tmp.x = i, tmp.y = j;
                Qst[ch-'0'].push(tmp);
            }
            else if (ch=='S')
            {
                st.x = i, st.y = j;
                st.d = 0;
            }
        }
    }
}

void solve(void)
{
    int ans = bfs();
    if (ans == -1)
        puts("Oh No!");
    else 
        printf("%d\n", ans);
}

int main()
{
    while (~scanf("%d", &n))
    {
        read();
        solve();
    }
    
    return 0;
}

/**/

posted on 2012-08-02 08:36  getgoing  阅读(211)  评论(0编辑  收藏  举报

导航