Question

In: Computer Science

I want to know the details interpretation of this code for my interview preperation on this...

I want to know the details interpretation of this code for my interview preperation on this code. This is A* algorithm in c++

#include<bits/stdc++.h>
using namespace std;
#define DISCONNECTED -1
int num_of_node,num_of_edge,graph[30][30],pathCost[30];
void init_Heuristic();

struct Node{
    int from,to;
    int cost;
};
struct CompareNode{
    bool operator()(Node& n1, Node& n2){
        if(n1.cost > n2.cost)return true;
        return false;
    }
};
map<int,int>Heuristic;
priority_queue<Node, vector<Node>, CompareNode> PQ;
vector<Node>path;
void AStarSearch(int source,int destination){

    init_Heuristic();
    for(int i = 1; i <= num_of_node; i++){
        if(graph[source][i] != DISCONNECTED){
            Node n;
            n.from = source;
            n.to = i;
            n.cost = graph[source][i] + Heuristic[i];
            pathCost[i] = graph[source][i];
            PQ.push(n);
        }
    }
    while(!PQ.empty()){
        Node tmp = PQ.top();
        path.push_back(tmp);
        if(tmp.to == destination)break;
        PQ.pop();
        for(int i = 1; i <= num_of_node; i++){
            if(graph[tmp.to][i] != DISCONNECTED){
                Node n;
                n.from = tmp.to;
                n.to = i;
                n.cost = pathCost[tmp.to] + graph[tmp.to][i] + Heuristic[i];
                pathCost[i] = pathCost[tmp.to] + graph[tmp.to][i];
                PQ.push(n);
            }
        }
    }
}
int main(){

    int a,b,c,source,destination;

    cout << "Enter Node: " << endl;
    cin >> num_of_node;
    cout << "Enter Edge: " << endl;
    cin >> num_of_edge;
    for(int i=1; i<=num_of_node; i++)
for(int j=1; j<=num_of_node; j++)
   graph[i][j] = DISCONNECTED;

    for(int i = 0; i < num_of_edge; i++){
        cin >> a >> b >> c;
        graph[a][b] = c;
    }
    cout << "Enter source: " << endl;
    cin >> source;
    cout << "Enter destination: " << endl;
    cin >> destination;
    AStarSearch(source,destination);
    for(int i = 0; i < path.size(); i++)
        cout << path.at(i).from << " -> " << path.at(i).to << " = " << path.at(i).cost << endl;
    return 0;
}
void init_Heuristic(){

    ///straight line distance ///

    Heuristic[1] = 10;
    Heuristic[2] = 5;
    Heuristic[3] = 0;
    Heuristic[4] = 13;

}

Solutions

Expert Solution

Consider a square grid having many obstacles and we are given a starting cell and a target cell. We want to reach the target cell (if possible) from the starting cell as quickly as possible. Here A* Search Algorithm comes to the rescue.

What A* Search Algorithm does is that at each step it picks the node according to a value-‘f’ which is a parameter equal to the sum of two other parameters – ‘g’ and ‘h’. At each step it picks the node/cell having the lowest ‘f’, and process that node/cell.

We define ‘g’ and ‘h’ as simply as possible below

g = the movement cost to move from the starting point to a given square on the grid, following the path generated to get there.
h = the estimated movement cost to move from that given square on the grid to the final destination. This is often referred to as the heuristic, which is nothing but a kind of smart guess. We really don’t know the actual distance until we find the path, because all sorts of things can be in the way (walls, water, etc.).


Related Solutions

this is my code I want the opposite i want to convert a postfix expression to...
this is my code I want the opposite i want to convert a postfix expression to infix expression #include <iostream> #include <string> #define SIZE 50 using namespace std; // structure to represent a stack struct Stack {   char s[SIZE];   int top; }; void push(Stack *st, char c) {   st->top++;   st->s[st->top] = c; } char pop(Stack *st) {   char c = st->s[st->top];   st->top--;   //(A+B)*(C+D)   return c; } /* function to check whether a character is an operator or not. this function...
Python I want to name my hero and my alien in my code how do I...
Python I want to name my hero and my alien in my code how do I do that: Keep in mind I don't want to change my code except to give the hero and alien a name import random class Hero:     def __init__(self,ammo,health):         self.ammo=ammo         self.health=health     def blast(self):         print("The Hero blasts an Alien!")         if self.ammo>0:             self.ammo-=1             return True         else:             print("Oh no! Hero is out of ammo.")             return False     def...
I am currently pursuing my chemical engineering degree. I want to know, if i want work...
I am currently pursuing my chemical engineering degree. I want to know, if i want work in chemical industry in future, what are the most important Subject (specific topic) / concept which are important from industry perspective (list them). Also list some of most important book that every chemical engineer should have. Thankyou!!
This is my code I want the average temp for the week to be printed when...
This is my code I want the average temp for the week to be printed when the user types : 'week' currently when the user types  'week' it only prints  Monday - Sunday and the average temp for each day. import java.util.Arrays; import java.util.ArrayList; import java.util.Scanner; public class weeklytemps {    public static void main(String[] args) {        Scanner input = new Scanner(System.in);                  ArrayList Day = new ArrayList(Arrays.asList(    "Monday","Tuesday","Wednesday","Thurday","Friday","Saturday","Sunday")); // Stores days of the week...
I know how to do this with arrays, but I have trouble moving my code to...
I know how to do this with arrays, but I have trouble moving my code to use with linked lists Write a C program that will deal with reservations for a single night in a hotel with 3 rooms, numbered 1 to 3. It must use an infinite loop to read commands from the keyboard and quit the program (return) when a quit command is entered. Use a switch statement to choose the code to execute for a valid command....
I don't know why my java code is not running this error code pops up -->...
I don't know why my java code is not running this error code pops up --> Error: Could not find or load main class DieRoll Caused by: java.lang.ClassNotFoundException: DieRoll. Code below:    import java.util.Random;    import java.util.Scanner;    public class Assignment {    public static void combineStrings() {    String school = "Harvard";    String city = "Boston, MA";    int stringLen;       String upper, changeChar, combine;       stringLen = school.length();    System.out.println(school+" contains "+stringLen+" characters." );   ...
I already have the code of this program, I just want to know how to fix...
I already have the code of this program, I just want to know how to fix the code to Implement the 5th function (System.nanotime() and System.currentTimeMillis() methods) What Code does: Introduction Searching is a fundamental operation of computer applications and can be performed using either the inefficient linear search algorithm with a time complexity of O (n) or by using the more efficient binary search algorithm with a time complexity of O (log n). Task Requirements In this lab, you...
hi i do not know what is wrong with my python code. this is the class:...
hi i do not know what is wrong with my python code. this is the class: class Cuboid: def __init__(self, width, length, height, colour): self.__width = width self.__length = length self.__height = height self.__colour = colour self.surface_area = (2 * (width * length) + 2 * (width * height) + 2 * (length * height)) self.volume = height * length * width def get_width(self): return self.__width def get_length(self): return self.__length def get_height(self): return self.__height def get_colour(self): return self.__colour def set_width(self,...
My code is working fine but after selecting an option and at the end I want...
My code is working fine but after selecting an option and at the end I want user could enter another option again without going back to menu. However, in my code when I enter another option, it prints the whole menu again then I can select option.Could anyone help me on that? #include "stdafx.h" #include #include #include using namespace std; const double pi = 3.14159265358979323846; const double deg_to_rad = (pi / 180); int main() { int option; do { cout...
In python I have my code written and I want just 4 functions to be fix...
In python I have my code written and I want just 4 functions to be fix in my code according to rule. My code is running but it has some problem regarding to rules. (I have did all the other things so you do not have to worry about other functions) 1) all the players has to play until he/she reaches to at least 500 points in first round. When user reach 500 points for the first time, user may...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT