Question

In: Computer Science

C++ CODE ONLY Using the following code. #include <iostream> #include <string> #include <climits> #include <algorithm> using...

C++ CODE ONLY

Using the following code.

#include <iostream>
#include <string>
#include <climits>
#include <algorithm>
using namespace std;

// M x N matrix
#define M 5
#define N 5

// Naive recursive function to find the minimum cost to reach
// cell (m, n) from cell (0, 0)
int findMinCost(int cost[M][N], int m, int n)
{
   // base case
   if (n == 0 || m == 0)
       return INT_MAX;

   // if we're at first cell (0, 0)
   if (m == 1 && n == 1)
       return cost[0][0];

   // include cost of the current cell in path and recur to find minimum
   // of the path from adjacent left cell and adjacent top cell.
   return min (findMinCost(cost, m - 1, n), findMinCost(cost, m, n - 1))
               + cost[m - 1][n - 1];
}

int main()
{
   int cost[M][N] =
   {
       { 4, 7, 8, 6, 4 },
       { 6, 7, 3, 9, 2 },
       { 3, 8, 1, 2, 4 },
       { 7, 1, 7, 3, 7 },
       { 2, 9, 8, 9, 3 }
   };

   cout << "The minimum cost is " << findMinCost(cost, M, N);

   return 0;
}

Answer the following questions:

Given a M x N matrix where each cell has a cost associated with it, find the minimum cost to reach last cell (0,0) of the matrix from its first cell (M,N). We can only move one unit right or one unit down from any cell. i.e. from cell (I,j), we can move to (i, j-1) or (i-1,j).

  1. Suppose that are also allowed to move diagonally to lower-right cell as well as downward and right. Find the minimum cost using pure recursion. (30 points)

Example output:

Minimum cost is 34.

Solutions

Expert Solution

#include <bits/stdc++.h>

using namespace std;

#define ROW 5

#define COL 5

struct cell

{

    int x, y;

    int distance;

    cell(int x, int y, int distance) :

        x(x), y(y), distance(distance) {}

};

bool operator<(const cell& a, const cell& b)

{

    if (a.distance == b.distance)

    {

        if (a.x != b.x)

            return (a.x < b.x);

        else

            return (a.y < b.y);

    }

    return (a.distance < b.distance);

bool isInsideGrid(int i, int j)

{

    return (i >= 0 && i < COL && j >= 0 && j < ROW);

}

int shortest(int grid[ROW][COL], int row, int col)

{

    int dis[row][col];

  

    for (int i = 0; i < row; i++)

        for (int j = 0; j < col; j++)

            dis[i][j] = INT_MAX;

     int dx[] = {-1, 0, 1, 0};

    int dy[] = {0, 1, 0, -1};

    set<cell> st;

  

    st.insert(cell(0, 0, 0));

    dis[0][0] = grid[0][0];

  

    while (!st.empty())

    {

  

        cell k = *st.begin();

        st.erase(st.begin());

        for (int i = 0; i < 4; i++)

        {

            int x = k.x + dx[i];

            int y = k.y + dy[i];

  

            if (!isInsideGrid(x, y))

                continue;

            if (dis[x][y] > dis[k.x][k.y] + grid[x][y])

            {

              

                if (dis[x][y] != INT_MAX)

                    st.erase(st.find(cell(x, y, dis[x][y])));

                dis[x][y] = dis[k.x][k.y] + grid[x][y];

                st.insert(cell(x, y, dis[x][y]));

            }

        }

    }

    for (int i = 0; i < row; i++, cout << endl)

        for (int j = 0; j < col; j++)

            cout << dis[i][j] << " ";

    

    return dis[row - 1][col - 1];

}

int main()

{

    int grid[ROW][COL] =

    {

        31, 100, 65, 12, 18,

        10, 13, 47, 157, 6,

        100, 113, 174, 11, 33,

        88, 124, 41, 20, 140,

        99, 32, 111, 41, 20

    };

    cout << shortest(grid, ROW, COL) << endl;

    return 0;

}


Related Solutions

C++ code Why my code is not compiling? :( #include <iostream> #include <iomanip> #include <string> using...
C++ code Why my code is not compiling? :( #include <iostream> #include <iomanip> #include <string> using namespace std; const int CWIDTH = 26; int main() {    int choice;    double convertFoC, converCtoF;    double starting, endvalue, incrementvalue;    const int CWIDTH = 13;    do {       cin >> choice;    switch (choice)    {        cin >> starting;    if (starting == 28){       cout << "Invalid range. Try again.";    }    while (!(cin >> starting)){       string  garbage;       cin.clear();       getline(cin, garbage);       cout << "Invalid data Type, must be a number....
For C++ Consider the following code defining classes for assets and office equipment: #include<string> #include<iostream> using...
For C++ Consider the following code defining classes for assets and office equipment: #include<string> #include<iostream> using namespace std; // class definition for asset class Asset{ protected: int value; // value of asset in cents public: Asset(int value); // constructor int get_value(); // get the value }; Asset::Asset(int val){ // implementation of constructor value=val; } int Asset::get_value(){ // implementation of get_value return value; } // abstract class for office equipment class OfficeEquipment:public Asset{ public: OfficeEquipment(int val); // constructor virtual void use_item()...
Complete the following TODO: parts of the code in C++ #include <iostream> #include <string> #include <limits>...
Complete the following TODO: parts of the code in C++ #include <iostream> #include <string> #include <limits> #include <vector> using namespace std; // // CLASS: NODE // class Node{ public: int value = 0; // our node holds an integer Node *next = nullptr; // our node has a pointer to the next Node Node(int i){ // contructor for our Node class value = i; // store a copy of argument "i" in "value" next = nullptr; // be sure next...
C++ finish the AVL Tree code: #include "AVLNode.h" #include "AVLTree.h" #include <iostream> #include <string> using namespace...
C++ finish the AVL Tree code: #include "AVLNode.h" #include "AVLTree.h" #include <iostream> #include <string> using namespace std; AVLTree::AVLTree() { root = NULL; } AVLTree::~AVLTree() { delete root; root = NULL; } // insert finds a position for x in the tree and places it there, rebalancing // as necessary. void AVLTree::insert(const string& x) { // YOUR IMPLEMENTATION GOES HERE } // remove finds x's position in the tree and removes it, rebalancing as // necessary. void AVLTree::remove(const string& x) {...
--- TURN this Code into Java Language --- #include <iostream> #include <string> using namespace std; //...
--- TURN this Code into Java Language --- #include <iostream> #include <string> using namespace std; // constants const int FINAL_POSITION = 43; const int INITIAL_POSITION = -1; const int NUM_PLAYERS = 2; const string BLUE = "BLUE"; const string GREEN = "GREEN"; const string ORANGE = "ORANGE"; const string PURPLE = "PURPLE"; const string RED = "RED"; const string YELLOW = "YELLOW"; const string COLORS [] = {BLUE, GREEN, ORANGE, PURPLE, RED, YELLOW}; const int NUM_COLORS = 6; // names...
Add Bubble Sorting & Binary Search Functions to the following code (C++) #include<iostream> #include<fstream> #include<string> #include<iomanip>...
Add Bubble Sorting & Binary Search Functions to the following code (C++) #include<iostream> #include<fstream> #include<string> #include<iomanip> #include<algorithm> using namespace std; const int row = 10; const int col = 7;   ifstream name; ifstream grade; ofstream out; void readData(string stname[row], int stgrade[row][col]); void stsum(int stgrade[row][col], int total[row]); void staverage(int total[row], double average[row]); void stlettergrade(double average[row],char ltrgrade[row]); void displayData(string stname[row], int stgrade[row][col], int total[row], double staverage[row], char ltrgrade[row]); void swapltrgrade(char* xp, char* yp); int main() {    int STG[row][col] = { {0},{0}...
write the algorithm for this the code?!. #include<iostream> using namespace std; #include<string.h> int main() { char...
write the algorithm for this the code?!. #include<iostream> using namespace std; #include<string.h> int main() { char plain[50], cipher[50]="", decrypt[50]=""; int subkeys[50], len;       cout<<"Enter the plain text:"<<endl; cin>>plain;    cout<<"Enter the first subkey:"<<endl; cin>>subkeys[0];    _strupr(plain);    len = strlen(plain);    /**********Find the subkeys**************/    for(int i=1; i<len; i++) { if ((plain[i-1]>='A') && (plain[i-1]<='Z')) { subkeys[i] = plain[i-1]-65; } }    /****************ENCRYPTION***************/       for(int i=0; i<len; i++) { if ((plain[i]>='A') && (plain[i]<='Z')) {    cipher[i] = (((plain[i]-65)+subkeys[i])%26)+65; }...
What is the flowchart for this code. Thank You! #include<iostream> #include<iomanip> #include<string> #include<cmath> using namespace std;...
What is the flowchart for this code. Thank You! #include<iostream> #include<iomanip> #include<string> #include<cmath> using namespace std; float series(float r[], int n) {    float sum = 0;    int i;    for (i = 0; i < n; i++)        sum += r[i];    return sum; } float parallel(float r[], int n) {    float sum = 0;    int i;    for (i = 0; i < n; i++)        sum = sum + (1 / r[i]);...
A C++ question: I want to indent the code of this C++ program: #include<iostream> #include<cstring> using...
A C++ question: I want to indent the code of this C++ program: #include<iostream> #include<cstring> using namespace std; int lastIndexOf(char *s, char target) { int n=strlen(s); for(int i=n-1;i>=0;i--) { if(s[i]==target) { return i; } } return -1; } void reverse(char *s) { int n=strlen(s); int i=0,j=n-1; while(i<=j) { char temp=s[i]; s[i]=s[j]; s[j]=temp; i++; j--; } return; } int replace(char *s, char target, char replacementChar) { int len=strlen(s); int total=0; for(int i=0;i<len;i++) { if(s[i]==target) { s[i]=replacementChar; total+=1; } } return total;...
In C++, assuming you have the following incomplete code: #include<iostream> #include <unistd.h> using namespace std; //...
In C++, assuming you have the following incomplete code: #include<iostream> #include <unistd.h> using namespace std; // Structure for storing the process data struct procData { char pname[5]; // Name of a process int arrivt; //Arrival time of a process int pburst; // Burst time of a process int endtime; // Exit time/ Leaving time of a process int remburst; // Remaining burst time of a process int readyFlag; // boolean, Flag for maintaining the process status }; // Global variable...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT