0

I have problem in unweighted undirected graph the question ask if any path between two point in binary matrix, the user insert the matrix and the cell in matrix to test

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;
}

In hacker rank some test not work properly because timeout. Any one can help please?

Blastfurnace
  • 18,411
  • 56
  • 55
  • 70
  • *"How I make bfs more efficient in cpp"*, at first take `std::vector` by const reference, instead of by value. – Jarod42 Dec 19 '20 at 22:25
  • `bool visited[n][m];` is invalid C++ as using VLA extension. – Jarod42 Dec 19 '20 at 22:40
  • 1
    "_In hacker rank some test not work properly because timeout._": please provide the link to the hacker rank problem. – AcK Dec 20 '20 at 06:32

1 Answers1

0

Idea 1: if what you need is find out "if there is a path", then it is really not necessary to use a BFS algorithm. There is overhead, a lot of overhead in queue operation.

Just do a nested loop, for every A,B,C where [A,B] is connect, and [B,C] is connected, mark C[A,c] as well. Sort of like dynamic programming. And finally return the connection between the two input nodes.

BFS is only needed when there exists some choice that are better than others. It is not the case in this problem.

Ruoyun Huang
  • 173
  • 10
  • Your nested loops seems worse than BFS. at least `O(n**3)`, I would say `O(n**4)` ... whereas BFS visit O(N) nodes... – Jarod42 Dec 19 '20 at 22:54