Finding path between two nodes in a graph using BFS and DFS - graph-algorithm

I'm following following links.
DFS: http://algs4.cs.princeton.edu/code/edu/princeton/cs/algs4/DepthFirstPaths.java.html
where pathTo methods is like this
public Iterable<Integer> pathTo(int v) {
validateVertex(v);
if (!hasPathTo(v)) return null;
Stack<Integer> path = new Stack<Integer>();
for (int x = v; x != s; x = edgeTo[x])
path.push(x);
path.push(s);
return path;
}
BFS: http://algs4.cs.princeton.edu/code/edu/princeton/cs/algs4/BreadthFirstPaths.java.html
where pathTo method is like this
public Iterable<Integer> pathTo(int v) {
validateVertex(v);
if (!hasPathTo(v)) return null;
Stack<Integer> path = new Stack<Integer>();
int x;
for (x = v; distTo[x] != 0; x = edgeTo[x])
path.push(x);
path.push(x);
return path;
}
My doubt is why for (x = v; distTo[x] != 0; x = edgeTo[x]) is used in BFS and for (int x = v; x != s; x = edgeTo[x]) in DFS. What will go wrong if I use x != s instead of distTo[x] != 0 in BFS's pathTo method ?

You are right in your observation, that the conditions x != s and distTo[x] != 0 are interchangeable. The reason is distTo[s] is 0, so loop breaks when we encounter the source vertex. So to break the loop when we encounter the source vertex, either of the two conditions will work.

Related

Dart store prime numbers in array

May I know how to store the N prime numbers, which I got from for loop in an array in dart?
import 'dart:io';
void main() {
// print('enter a start number');
// int a = int.parse(stdin.readLineSync()!);
print('enter a number');
int b = int.parse(stdin.readLineSync());
print('this are prime numbers');
primenum(b);
var z = '';
}
primenum(b) {
String string = "";
int a = 2;
outerLoop:
for (int i = a; i <= b; i++) {
for (int x = 2; x <= i / a; x++) {
if (i % x == 0) {
continue outerLoop;
}
}
var z = i.toString();
// print(z);
var h = z;
// String str = '';
string = string + h;
}
List d = string.split('');
print(d);
}
Using the above code, I am able to get those numbers in List. But the double-digit numbers are splitting.
May I know How to solve the above task? using dart.
The way you're doing string.split is splitting the string into a list of each individual character. Instead, you can add each prime number to a List directly without doing string manipulation.
primenum(b) {
List<String> d;
int a = 2;
outerLoop:
for (int i = a; i <= b; i++) {
for (int x = 2; x <= i / a; x++) {
if (i % x == 0) {
continue outerLoop;
}
}
d.add(i.toString());
}
print(d);
}

Itrying to find the path of a node in a binary tree by a vector function but I am getting only 2 values from the starting node in output of the vector

I am trying to find the path of a node in a binary tree by a
vector function but I am getting only 2 values from the of
starting of the node in output of the vector
like I am trying to find the path of the node 10 and my output
would be in the following way---(1 3 7 9 10),but I am getting
only (1 3) in the output
#include <bits/stdc++.h>
using namespace std;
struct node
{
int data;
struct node *left;
struct node *right;
node(int val)
{
data = val;
left = NULL;
right = NULL;
}
};
vector<int> path(node *root, int x)
{
static vector<int> v;
if (root == NULL)
{
return v;
}
v.push_back(root->data);
if (root->data == x)
{
v.push_back(x);
return v;
}
path(root->left, x);
path(root->right, x);
v.pop_back();
return v;
}
int main()
{
struct node *root = new node(1);
root->left = new node(2);
root->right = new node(3);
root->left->left = new node(4);
root->left->right = new node(5);
root->left->right->left = new node(11);
root->right->left = new node(6);
root->right->right = new node(7);
root->right->right->right = new node(9);
root->right->right->right->right = new node(10);
int x = 10;
vector<int> v = path(root, x);
cout << v.size();
cout << endl;
for (int i = 0; i < v.size(); i++)
{
cout << v[i] << " ";
}
return 0;
}

Network Delay Problem - Complexity Analysis

Below is a solution Network delay problem of leetcode. I have written a all test case success solution. But not able to analyse the time complexity. I believe its O(V^2 + E) where V is the number of nodes and E edges.
In this solution though I am adding all adjacents of each node every time, but not processing them further if there exists a min distance for that node already.
Leetcode question link https://leetcode.com/problems/network-delay-time
public int networkDelayTime(int[][] times, int n, int k) {
int[] distances = new int[n+1];
Arrays.fill(distances , -1);
if(n > 0){
List<List<int[]>> edges = new ArrayList<List<int[]>>();
for(int i = 0 ; i <= n ; i++){
edges.add(new ArrayList<int[]>());
}
for(int[] time : times){
edges.get(time[0]).add(new int[]{time[1] , time[2]});
}
Queue<Vertex> queue = new LinkedList<>();
queue.add(new Vertex(k , 0));
while(!queue.isEmpty()){
Vertex cx = queue.poll();
int index = cx.index;
int distance = cx.distance;
//process adjacents only if distance is updated
if(distances[index] == -1 || distances[index] > distance){
distances[index] = distance;
List<int[]> adjacents = edges.get(index);
for(int[] adjacent : adjacents){
queue.add(new Vertex(adjacent[0] , adjacent[1]+distance));
}
}
}
}
int sum = 0;
for(int i = 1 ; i <= n; i++){
int distance = distances[i];
if(distance == -1){
return -1;
}
sum = Math.max(sum , distance);
}
return sum;
}
public static class Vertex{
int index;
int distance;
public Vertex(int i , int d){
index = i;
distance = d;
}
}
You should use PriorityQueue instead of LinkedList

Round Robin Algorithm Using Circular Linked List

Use a circular singly linked list to implement Round Robin process scheduling algorithm in which
each process is provided a fixed time (quantum) to execute and is pre-empted after that time period
to allow the other process to execute. Assume a set of ‘n’ processes are ready for execution.
Read the time quantum and for each of the processes, read the total execution time.
Name the processes as ‘A’, ‘B’ and so on in sequence. Each node should contain the name
of the process, its total execution time and the remaining execution time. If a process
completes its execution, remove it from the list after displaying its name and the
completion time.
Input format:
First line contains the value of ‘n’, the number of processes
Second line contains the time quantum
The remaining lines contain the total execution time of the processes in order.
5
2
6
3
7
5
1
Output:
E 9
B 12
A 18
D 21
C 22
#include <iostream>
using namespace std;
class node
{
public:
char name;
int tm;
int rt;
node *next;
};
class rr
{
public:
node * Head = NULL;
int j = 65;
void insert (int n)
{
node *nn = new node;
nn->name = j++;
nn->tm = n;
nn->rt = nn->tm;
if (Head == NULL)
{
Head = nn;
Head->next = Head;
}
else
{
node *temp = Head;
while (temp->next != Head)
temp = temp->next;
nn->next = temp->next;
temp->next = nn;
}
}
void quantum (int t)
{
node *temp = Head;
int c = 0, i = 0;
while (Head != NULL)
{
{
temp->rt = temp->rt - t;
c = c + t;
if (temp->rt <= 0)
{
c = c + temp->rt;
cout << temp->name;
cout << c << endl;
del (temp->name);
if (temp->next == temp)
{
break;
}
}
temp = temp->next;
}
}
}
void del (char x)
{
node *p = NULL;
node *temp = Head;
if (Head->name == x)
{
while (temp->next != Head)
temp = temp->next;
p = Head;
temp->next = Head->next;
Head = Head->next;
delete p;
}
else
{
while (temp->name != x)
{
p = temp;
temp = temp->next;
}
p->next = temp->next;
delete temp;
}
}
};
int
main ()
{
rr robin;
int i, n, x, y, t;
cin >> y;
cin >> t;
for (i = 0; i < y; i++)
{
cin >> n;
robin.insert (n);
}
robin.quantum (t);
return 0;
}

Why I cant solve this puzzle?

Im tring to solve this puzzle by using dart lang but I didint solve it and I got large number + error! There is an puzzle image to understand it from here
can you help or give me a tip to solve this puzzle ~!
See full code :
import 'dart:math';
void main() {
var value;
int loob = 0;
do {
var z = new Random().nextInt(20);
var x = new Random().nextInt(20);
var y = new Random().nextInt(20);
var n = new Random().nextInt(20);
if (z - x == 9) {
print('DONE LOOB1 Z = $z and X = $x');
do {
var x = new Random().nextInt(20);
var n = new Random().nextInt(20);
if (x + n == 2) {
print('DONE LOOB2 X = $x and n = $n ');
do {
var n = new Random().nextInt(20);
var y = new Random().nextInt(20);
if (y - n == 14) {
print('DONE LOOB3 y = $y and n = $n ');
do {
var z = new Random().nextInt(20);
var y = new Random().nextInt(20);
if (z - y == 12) {
print('DONE LOOB4 z = $z and y = $y ');
value = 1;
} else {}
} while (value != 1);
} else {}
} while (value != 1);
value = 1;
} else {}
} while (value != 1);
value = 1;
} else {
null;
}
print(++loob);
} while (value != 1);
}
reslate code :
DONE LOOB1 Z = 11 and X = 2
DONE LOOB2 X = 2 and n = 0
DONE LOOB3 y = 14 and n = 0
DONE LOOB4 z = 17 and y = 5
Finshed
this is your algorithm issue, you are adding 0.1 to your variable every step, and it means all numbers are equal in the end you must create two mathematical equations and two unknown values and then solve them. this is the main approach to solve such problems.
Assume this picture like these Equations:
x - y = 9
x + n = 2
y - n = 14
z - y = 12
now you have 4 equations and 4 unknown.
you can solve this equation by this (Matrix manipulation) or this (substitution one unknown with another) on method.

Resources