BFS实施不正常

时间:2014-01-25 08:00:10

标签: c++ algorithm shortest-path

这是我的BFS实现,它总是让我回归。我应该基本上找到通过这张地图的最短路径,1 - 意味着它是一堵墙,0 - 意味着没有墙。我在哪里错了?

class node { public: int x,y; };

int bfs(int x, int y)
{
    node start;
    int result = 0;
    start.x = 0;
    start.y = 0;
    std::queue<node> search_queue;
    bool visited[4][4];
    int map[4][4] = {
                    {0,1,0,1},
                    {0,0,0,0},
                    {1,0,1,0},
                    {0,1,0,0}
                };
    for(int i = 0 ; i < 4; i ++)
    {
        for(int j = 0 ; j < 4; j++)
        {
            visited[i][j] = false;
        }
    }
    search_queue.push(start);
    while(!search_queue.empty())
    {
        node top = search_queue.front();
        search_queue.pop();

        if (visited[top.x][top.y]) continue;
        if (map[top.x][top.y] == 1) continue;
            if (top.x < 0 || top.x >= 4) continue;
            if (top.y < 0 || top.y >= 4) continue;
        visited[top.x][top.y] = true;
        result++;
        node temp;

        temp.x = top.x+1;
        temp.y=top.y;
        search_queue.push(temp);

        temp.x = top.x-1;
        temp.y=top.y;
        search_queue.push(temp);

        temp.x = top.x;
        temp.y=top.y+1;
        search_queue.push(temp);

        temp.x = top.x;
        temp.y=top.y-1;
        search_queue.push(temp);
    }
    return result;
}

我从主要那样称呼它:cout<<bfs(0,0);

5 个答案:

答案 0 :(得分:2)

给定的代码产生10.通过一些修改,这里是live example。一个修改是将输入xy设置为起点,我猜这是Jonathan Leffler在上面指出的意图。第二个修改是现在进行范围检查推入队列之前,所以while循环修改如下:

    while(!search_queue.empty())
    {
        node top = search_queue.front();
        search_queue.pop();

        if (visited[top.x][top.y]) continue;
        if (map[top.x][top.y] == 1) continue;
        visited[top.x][top.y] = true;
        result++;
        node temp;

        temp.y = top.y;

        if (top.x < 3)
        {
            temp.x = top.x + 1;
            search_queue.push(temp);
        }

        if (top.x > 0)
        {
            temp.x = top.x - 1;
            search_queue.push(temp);
        }

        temp.x = top.x;

        if (top.y < 3)
        {
            temp.y = top.y + 1;
            search_queue.push(temp);
        }

        if (top.y > 0)
        {
            temp.y = top.y - 1;
            search_queue.push(temp);
        }
    }

现在,假设起点在范围内(并且您可以为此添加另一个检查),此循环将始终在范围内移动,并且它永远不会将超出范围的点放入队列中,从而节省了一些计算

此外,在您最初编写条件时,您可以在范围检查之前访问数组visitedmap ,这可能会产生错误结果。

最重要的是,如果您的目标是find the shortest path through this map,则此算法不合适。数字10是从(0,0)开始可以访问的所有位置的数量。它不是通往任何地方的最短路径。你需要的是一个最短路径算法,由于这里的图权重是正数,一个简单的选项是Dijsktra's algorithm

这只需要对您的代码进行一些修改,但我留给您。基本上,您需要用整数数组visited替换数组distance,指定从起始位置到每个点的最小距离,初始化为“无穷大”并且仅减小。并且您的队列必须由优先级队列替换,以便通过增加距离来访问点。

答案 1 :(得分:1)

检测路径

#include <iostream>
#include <queue>

class node { public: int x, y; };

int bfs(int x, int y)
{
    node start;
    int result = 0;
    start.x = x;
    start.y = y;
    std::queue<node> search_queue;
    bool visited[4][4];
    int map[4][4] =
    {
        {0, 1, 0, 1},
        {0, 0, 0, 0},
        {1, 0, 1, 0},
        {0, 1, 0, 0}
    };
    for (int i = 0; i < 4; i++)
    {
        for (int j = 0; j < 4; j++)
        {
            visited[i][j] = false;
        }
    }
    search_queue.push(start);
    while (!search_queue.empty())
    {
        node top = search_queue.front();
        search_queue.pop();

        if (visited[top.x][top.y])
            continue;
        if (map[top.x][top.y] == 1)
            continue;
        if (top.x < 0 || top.x >= 4)
            continue;
        if (top.y < 0 || top.y >= 4)
            continue;

        visited[top.x][top.y] = true;
        std::cout << "visit: [" << top.x << "][" << top.y << "]\n";
        result++;
        node temp;

        temp.x = top.x + 1;
        temp.y = top.y;
        search_queue.push(temp);

        temp.x = top.x - 1;
        temp.y = top.y;
        search_queue.push(temp);

        temp.x = top.x;
        temp.y = top.y + 1;
        search_queue.push(temp);

        temp.x = top.x;
        temp.y = top.y - 1;
        search_queue.push(temp);
    }
    return result;
}

int main()
{
    std::cout << bfs(0, 0);
}

产生

visit: [0][0]
visit: [1][0]
visit: [1][1]
visit: [2][1]
visit: [1][2]
visit: [0][2]
visit: [1][3]
visit: [2][3]
visit: [3][3]
visit: [3][2]
10

一个有趣的观点是它到达[3][3]并继续;你好像没有明确定义。这占了额外计数之一(与应该预期的7相比)。 [2][1][0][2]个死胡同代表另外两个。基本上,当你走到死路并到达终点时,你需要递减result

指定终点

通过answer看到iavr后,边界检查发生了变化。

#include <iostream>
#include <queue>

class node { public: int x, y; };

int bfs(int bx, int by, int ex, int ey)
{
    node start;
    int result = 0;
    start.x = bx;
    start.y = by;
    std::queue<node> search_queue;
    bool visited[4][4];
    int map[4][4] =
    {
        {0, 1, 0, 1},
        {0, 0, 0, 0},
        {1, 0, 1, 0},
        {0, 1, 0, 0}
    };
    for (int i = 0; i < 4; i++)
    {
        for (int j = 0; j < 4; j++)
        {
            visited[i][j] = false;
        }
    }
    search_queue.push(start);
    while (!search_queue.empty())
    {
        node top = search_queue.front();
        search_queue.pop();

        if (top.x < 0 || top.x >= 4)
            continue;
        if (top.y < 0 || top.y >= 4)
            continue;
        if (visited[top.x][top.y])
            continue;
        if (map[top.x][top.y] == 1)
            continue;

        visited[top.x][top.y] = true;
        std::cout << "visit: [" << top.x << "][" << top.y << "]\n";
        result++;

        if (top.x == ex && top.y == ey)
            break;

        node temp;

        temp.x = top.x + 1;
        temp.y = top.y;
        search_queue.push(temp);

        temp.x = top.x - 1;
        temp.y = top.y;
        search_queue.push(temp);

        temp.x = top.x;
        temp.y = top.y + 1;
        search_queue.push(temp);

        temp.x = top.x;
        temp.y = top.y - 1;
        search_queue.push(temp);
    }
    return result;
}

int main()
{
    std::cout << bfs(0, 0, 3, 3);
}

输出:

visit: [0][0]
visit: [1][0]
visit: [1][1]
visit: [2][1]
visit: [1][2]
visit: [0][2]
visit: [1][3]
visit: [2][3]
visit: [3][3]
9

获得正确答案

#include <iostream>
#include <queue>

class node { public: int x, y, l; };

int bfs(int bx, int by, int ex, int ey)
{
    node start;
    int result = 0;
    start.x = bx;
    start.y = by;
    start.l = 1;
    std::queue<node> search_queue;
    bool visited[4][4];
    int map[4][4] =
    {
        {0, 1, 0, 1},
        {0, 0, 0, 0},
        {1, 0, 1, 0},
        {0, 1, 0, 0}
    };
    for (int i = 0; i < 4; i++)
    {
        for (int j = 0; j < 4; j++)
        {
            visited[i][j] = false;
        }
    }
    search_queue.push(start);
    while (!search_queue.empty())
    {
        node top = search_queue.front();
        search_queue.pop();

        if (visited[top.x][top.y])
            continue;
        if (map[top.x][top.y] == 1)
            continue;
        if (top.x < 0 || top.x >= 4)
            continue;
        if (top.y < 0 || top.y >= 4)
            continue;

        visited[top.x][top.y] = true;
        std::cout << "visit: [" << top.x << "][" << top.y << "] = " << top.l << "\n";

        result = top.l;
        if (top.x == ex && top.y == ey)
            break;

        node temp;

        temp.l = top.l + 1;

        temp.x = top.x + 1;
        temp.y = top.y;
        search_queue.push(temp);

        temp.x = top.x - 1;
        temp.y = top.y;
        search_queue.push(temp);

        temp.x = top.x;
        temp.y = top.y + 1;
        search_queue.push(temp);

        temp.x = top.x;
        temp.y = top.y - 1;
        search_queue.push(temp);
    }
    return result;
}

int main()
{
    std::cout << bfs(0, 0, 3, 3) << std::endl;
}

输出:

visit: [0][0] = 1
visit: [1][0] = 2
visit: [1][1] = 3
visit: [2][1] = 4
visit: [1][2] = 4
visit: [0][2] = 5
visit: [1][3] = 5
visit: [2][3] = 6
visit: [3][3] = 7
7

答案 2 :(得分:1)

您的代码只计算可访问单元格的数量。我假设您只想计算开始和结束之间的单元格(result变量在此上下文中无用)。我通常使用这样的数据结构:

std::queue<pair<node,int> > search_queue;

从队列中提取元素时,代码如下所示:

    node top = search_queue.front().first;
    int current_length = search_queue.front().second;
    // if (top == end) return current_length;  (this is the value you are interested in)

将下一个元素添加到队列中当然是这样的:

    search_queue.add(make_pair(temp, current_length + 1));

我希望完整的代码很容易从这里获得。

答案 3 :(得分:0)

我认为你必须调试类“node”的赋值结果。 它可能不起作用。

为此,您可以重载运算符“=”并添加一个默认构造函数,其参数参数类型为“node”。

答案 4 :(得分:0)

另一种方法

class Queue:
    def __init__(self):
            self.items=[]
    def enqueue(self,item):
            self.items.append(item)
    def dequeue(self):
            return self.items.pop(0)
    def isEmpty(self):
            return self.items==[]
    def size(self):
            return len(self.items)

class Vertex:
    def __init__(self,id):
            self.id=id
            self.color="white"
            self.dist=None
            self.pred=None
            self.sTime=0
            self.fTime=0
            self.connectedTo={}

    def addNeighbor(self,nbr,weight):
            self.connectedTo[nbr]=weight
    def __str__(self):
            return str(self.id)+"connectedTo"+str([x for x in self.connectedTo])
    def getConnection(self):
            return self.connectedTo.keys()
    def getId(self):
            return self.id
    def getWeight(self,nbr):
            return self.connectedTo[nbr]
    def setColor(self,c):
            self.color=c
    def getColor(self):
            return self.color
    def setDistance(self,d):
            self.dist=d
    def getDistance(self):
            return self.dist
    def setPred(self,u):
            self.pred=u
    def getPred(self):
            return self.pred
    def getsTime(self):
            return self.sTime
    def getfTime(self):
            return self.fTime
    def setsTime(self,t):
            self.sTime=t
    def setfTime(self,t):
            self.fTime=t

class Graph:
    def __init__(self):
            self.vertList={}
            self.numVertices=0
            self.time=0
    def addVertex(self,id):
            self.numVertices=self.numVertices+1
            newVertex=Vertex(id)
            self.vertList[id]=newVertex
    def getVertex(self,id):
            if id in self.vertList:
                    return self.vertList[id]
            else:
                    return None
    def __contains__(self,id):
            return id in self.vertList
    def addEdge(self,u,v,weight=0):
            if u not in self.vertList:
                    self.addVertex(u)
            if v not in self.vertList:
                    self.addVertex(v)
            self.vertList[u].addNeighbor(self.vertList[v],weight)
    def getVertices(self):
            return self.vertList.keys()
    def __iter__(self):
            return iter(self.vertList.values())
    def bfs(self,start):
            self.vertList[start].setDistance(0)
            self.vertList[start].setColor("gray")
            q=Queue()
            q.enqueue(self.vertList[start])
            while(q.size()>0):
                    u=q.dequeue()
                    u.setColor("black")
                    for v in u.connectedTo:
                            if v.getColor()=="white":
                                    v.setColor("gray")
                                    v.setDistance(u.getDistance()+1)
                                    v.setPred(u)
                                    q.enqueue(v)

                    print"Id ",u.getId()," color ",u.getColor()," Distance ",u.getDistance()