Tuesday, March 14, 2017

#codingexercise
Find the shortest path with exactly k edges in a directed and weighted graph
int GetShortestPath(int[,] graph, int u, int v, int k)
{
if (k == 0 && u == v) return 0;
if (k == 1 && graph[u,v] != int_max) return graph[u,v];
if (k <= 0) return int_max;
int res = int_max;
for (int i = 0; i < graph.Vertices; i++)
{
if  (graph[u,i] != int_max && u != i && v != i)
{
    int rec  = GetShortestPath(graph, i, v, k-1);
    if (rec != int_max)
         res = min(res, graph[u,i] + rec);
}
}
return res;

}
Given a positive integer N, count the number of binary strings without consecutive 1s
int GetCount(int n)
{
var a = int[n]; // number of required strings ending in 0
var b = int[n]; // number of required strings ending in 1
for (int i = 1; i < n; i++)
{
a[i] = a [i-1] + b[i-1];
b[i] = a[i-1];
}
return a[n-1]+b[n-1];
}

No comments:

Post a Comment