GRAPH
GRAPH
BFS:
Same as level order traversal of tree
Code:
int numProvinces(vector<vector<int>>& adj, int V) {
vector<int> visited(V, 0); // Initialize visited array with 0
int ans = 0;
queue<int> q;
while (!q.empty()) {
int curr = q.front();
q.pop();
return ans;
}
DFS:
Same as pre order traversal of tree
Code:
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
// Function to return a list containing the DFS traversal of the graph.
vector<int>ans;
void dfs(int x,vector<int> adj[],vector<int> &visited,int V){
visited[x]=1;
ans.push_back(x);
for(int i=0;i<adj[x].size();i++){
if(visited[adj[x][i]]!=1){
dfs(adj[x][i],adj,visited,V);
}
}
vector<int> dfsOfGraph(int V, vector<int> adj[]) {
vector<int >visited(V,0);
dfs(0,adj,visited,V);
return ans;
}
};
Problem 1]:
delete[] visited;
return ans;
}
DIJSKTRA ALGORITHM :
vector<int >dis(V,INT_MAX);
dis[S]=0;
pq.push({0,S});
while(!pq.empty()){
int edgedistance=pq.top().first;
int node=pq.top().second;
pq.pop();
for(int j=0;j<adj[node].size();j++){
int adjdis=adj[node][j][1];
int adjnode=adj[node][j][0];
if(edgedistance+adjdis<dis[adjnode]){
pq.push({adjdis+edgedistance,adjnode});
dis[adjnode]=adjdis+edgedistance;
}
}
}
return dis;
}
Problem Statement: You are given an undirected weighted graph of n nodes (0-
indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge
connecting the nodes a and b with a probability of success of traversing that
edge succProb[i].
Given two nodes start and end, find the path with the maximum probability of success
to go from start to end and return its success probability.
If there is no path from start to end, return 0. Your answer will be accepted if it differs
from the correct answer by at most 1e-5.
while (!pq.empty()) {
pair<double, int> p = pq.top();
pq.pop();
return dis[end];
}