我如何使 bfs 在 cpp 中更有效率

问题描述

我在未加权的无向图中遇到问题,该问题询问二进制矩阵中两点之间是否有任何路径,用户插入矩阵和矩阵中的单元格进行测试

bool BFS(vector<vector<int>>mat,Point src,Point dest,int n,int m)
{
    
    if (!mat[src.x][src.y] || !mat[dest.x][dest.y])
        return 0;
    
    bool visited[n][m];
    memset(visited,false,sizeof visited);
    
    
    visited[src.x][src.y] = true;
    
    
    queue<queueNode> q;
    
    queueNode s = {src};
    q.push(s);
    
    while (!q.empty())
    {
        queueNode curr = q.front();
        Point pt = curr.pt;
        
        
        if (pt.x == dest.x && pt.y == dest.y)
            return 1;
        
        
        q.pop();
        
        for (int i = 0; i < 8; i++)
        {
            int row = pt.x + rowNum[i];
            int col = pt.y + colNum[i];
            
            if (isValid(row,col,n,m) && mat[row][col] &&
                !visited[row][col])
            {
                
                visited[row][col] = true;
                queueNode Adjcell =  {row,col};
                q.push(Adjcell);
            }
        }
    }
    
    
    return 0;
}

在黑客排名中,由于超时,一些测试无法正常工作。 有人可以帮忙吗?

解决方法

想法1:如果你需要的是找出“是否有路径”,那么实际上没有必要使用BFS算法。有开销,队列操作的开销很大。

只需做一个嵌套循环,对于每个 A,B,C,其中 [A,B] 是连接的,而 [B,C] 是连接的,也标记 C[A,c]。有点像动态规划。最后返回两个输入节点之间的连接。

只有当存在一些比其他选择更好的选择时才需要 BFS。本题并非如此。