Certainly! Below is a C++ program that simulates the spread of rot in an orchard over a specified number of days. The orchard is represented as a 2D grid where each cell can be empty ('_'), have a healthy tree ('y'), or have a rotten tree ('p'). Each day, the rot spreads to adjacent healthy trees (up, down, left, right).
#include <iostream>
#include <vector>
using namespace std;
// Function to simulate the spread of rot in the orchard
vector<vector<char>> simulateRottenOrchard(vector<vector<char>>& orchard, int days) {
int rows = orchard.size();
if (rows == 0) return orchard;
int cols = orchard[0].size();
// Directions: up, down, left, right
vector<pair<int, int>> directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
// Simulate day by day
for (int day = 0; day < days; ++day) {
// Create a copy of the orchard to store updates
vector<vector<char>> newOrchard = orchard;
// Traverse each cell in the orchard
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (orchard[i][j] == 'p') {
// Spread rot to adjacent healthy trees
for (auto dir : directions) {
int newRow = i + dir.first;
int newCol = j + dir.second;
if (newRow >= 0 && newRow < rows && newCol >= 0 && newCol < cols) {
if (orchard[newRow][newCol] == 'y') {
newOrchard[newRow][newCol] = 'p';
}
}
}
}
}
}
// Update orchard for the next day
orchard = newOrchard;
}
return orchard;
}
int main() {
// Example orchard
vector<vector<char>> orchard = {
{'_', 'y', 'y', '_', 'p'},
{'y', 'y', 'y', 'y', 'y'},
{'_', 'y', 'p', '_', 'y'},
{'y', '_', 'y', 'y', '_'},
{'p', 'y', '_', '_', 'y'}
};
int days = 3;
cout << "Initial Orchard:\n";
for (auto row : orchard) {
for (auto cell : row) {
cout << cell << ' ';
}
cout << endl;
}
// Simulate the spread of rot
vector<vector<char>> result = simulateRottenOrchard(orchard, days);
cout << "\nOrchard after " << days << " days:\n";
for (auto row : result) {
for (auto cell : row) {
cout << cell << ' ';
}
cout << endl;
}
return 0;
}
Explanation:
- We define the
simulateRottenOrchard function, which takes the current state of the orchard and the number of days to simulate.
- For each day, we iterate over the grid and whenever we find a rotten tree ('p'), we check its adjacent cells.
- If an adjacent cell has a healthy tree ('y'), we mark it as rotten in a new grid (
newOrchard), ensuring we don't use updated values in the same iteration.
- After processing all cells for the day, we update the orchard with the new grid.
- In the
main function, we test the simulation with an example orchard and print the state before and after the simulation.
Sample Output:
Initial Orchard:
_ y y _ p
y y y y y
_ y p _ y
y _ y y _
p y _ _ y
Orchard after 3 days:
_ p p _ p
p p p p p
_ p p _ p
p _ p p _
p p _ _ p
This program demonstrates how rot spreads over the orchard for the specified number of days. You can modify the orchard grid and days variable in the main function to test different scenarios.