BFS和DFS求最短路径的C++代码实现

数据结构体

struct node
{
    int x,y;
    int step;
};

安全函数

bool safe(node st)
{
    if(st.x >= 0 && st.y >= 0 && !vis[st.x][st.y] && map[st.x][st.y] != '#')
    return true;
    return false;
}

bfs实现

void bfs(node st)
{
    queueq;
    q.push(st);
    vis[st.x][st.y] = 1;
    node now,next;
    while(!q.empty())
    {
        now = q.front();
        q.pop();
        for(int i = 0;i < 4;i++)
        {
            next.x = now.x + dir[i][0];
            next.y = now.y + dir[i][1];

            if(safe(next))
            {
                vis[next.x][next.y] = 1;
                next.step = now.step + 1;
                q.push(next);
            }

            if(map[next.x][next.y] == 'e')  //到达出口
            {
                cout << "step = " << next.step << endl;
                return;
            }
        }
    }
}

DFS实现

void dfs(node st)
{
    if(map[st.x][st.y] == 'e')
    {
        cout << "step = " << st.step << endl;
        return;
    }
    node next;
    for(int i = 0;i < 4;i++)
    {
        next.x = st.x + dir[i][0];
        next.y = st.y + dir[i][1];
        if(safe(next))
        {
            vis[next.x][next.y] = 1;
            next.step = st.step + 1;
            dfs(next);
        }
    }
}

如果需要记录最短路径,并依次输出。首先需要遍历,这是无可厚非的。但是在遍历过程中需要添加一点东西。这东西的效果可以将地图路径用树模拟。这个‘东西’就是前置指针(*pre)。遍历中将该元素的父元素付给该前置指针。最后利用递归或vector输出,即可得到路径。

递归

void output(node *end)
{
    //从最后一个元素开始
    if(map[end -> x][end -> y] == 's')
    {
        printf("(%d,%d)",s.x,s.y);
        return;
    }
    node pre;
    pre = end -> pre ;
    output(pre);
    printf("(%d,%d)",end -> x,end -> y);
}

非递归

void output(node *end)
{
    vectorq;
    while(1)
    {
        q.push(*end);
        if(map[end -> x]][end -> y] == 's')
            break; 
        end = end -> pre;
    }
    for(int i = q.size();i >= 0;i--)
        printf("(%d,%d)\n",q[i].x,q[i].y);
}

你可能感兴趣的:(算法,C++)