6.4.2 走迷宫

利用bfs寻找最短路。通过对u/m得到x,u%m得到y。u = x * m + y
将方向保存在dx[], dy[]中。

c
int q[maxn*maxn]; void bfs(int x, int y) { int front = 0, rear = 0, d, u; u = x*m + y; vis[x][y] = 1; fa[x][y] = u; dist[x][y] = 0; q[rear++] = u; while(front < rear) { u = q[front++]; x = u/m; y = u %m; for(d = 0; d < 4; d++) { int nx = x + dx[d], ny = y + dy[d]; if (nx >= 0 && nx < n && ny >= 0 && ny <m && maze[nx][ny] && !vis[nx][ny]) { int v= nx * m + ny; q[rear++] = v; vis[nx][ny] = 1; fa[nx][ny] = u; dist[nx][ny] = dist[x][y]+1; last_dir[nx][ny] = d; } } } }

6.4.3 拓扑排序,DAG(Directed Acyclic Graph)有向无环图

c#include <stdio.h>
#include <string.h>

const int maxn = 1000;
const int maxm = 1000;

// 用于判断是否存在环
int c[maxn];
int topo[maxn], t;
int n, m;
int G[maxm][maxm];

bool dfs(int u)
{
    c[u] = -1;
    for(int v= 0; v < n; v++) if(G[u][v])
    {
        if(c[v] < 0) return false;
        else if(!c[v] && !dfs(v)) return false;
    }
    c[u] = 1; topo[--t] = u;
    return true;
}

bool toposort()
{
    t = n;
    memset(c, 0, sizeof(c));
    for(int u = 0; u < n; u++) if(!c[u])
        if(!dfs(u)) return false;
    return true;
}


int main()
{
    int u, v;
    while(~scanf("%d %d", &n, &m))
    {
        memset(G, 0, sizeof(G));
        memset(topo, 0, sizeof(topo));

        for(int i = 0; i < m; i++)
        {
            scanf("%d %d", &u, &v);
            G[u][v] = 1;
        }

        if(toposort())
        {
            for(int i = 0; i < n; i++)
                printf("%d ", topo[i]);
            printf("\n");
        } else 
        {
            printf("sort error\n");
        }
    }
    return 0;
}

svtter
209 声望37 粉丝

更喜欢原型开发


引用和评论

0 条评论