广度优先搜索模板(BFS)

来源:互联网 发布:徐志摩 金庸 知乎 编辑:程序博客网 时间:2024/05/21 15:06
在网上找了很久才找到这个代码,此代码用于理解广度优先搜索(BFS)的试题大家多理解
structNode{ 
    intx; 
    inty; 
    intstep; 
    Node(intx1,inty1,intstep1):x(x1),y(y1),step(step1){} 
}; 
intBFS() { 
    Node node(0,0,0); 
    queue<Node> q ; 
    while(!q.empty()) q.pop(); 
    q.push(node); 
    while(!q.empty()) { 
        node = q.front(); 
        q.pop(); 
        if(node.x == n-1 && node.y == n-1) { 
            returnnode.step; 
        
        visit[node.x][node.y] = 1; 
        for(inti = 0; i < 4; i++) { 
            intx = node.x + stepArr[i][0]; 
            inty = node.y + stepArr[i][1]; 
            if(x >= 0 && y >= 0 && x < n && y < n  
                        && visit[x][y] == 0 && mazeArr[x][y] == 0) { 
                visit[x][y] = 1; 
                Node next(x, y, node.step+1); 
                q.push(next); 
            
        
    
    return-1; 
0 0
原创粉丝点击