c++ 接雨水 可视化
时间: 2023-07-19 09:43:47 浏览: 63
接雨水是一道经典的算法问题,可以通过可视化来更好地理解。以下是一个基于C++的接雨水可视化示例:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <Windows.h>
using namespace std;
const int kScreenWidth = 100; // 屏幕宽度
const int kScreenHeight = 30; // 屏幕高度
void DrawBar(int x, int y, int height, char ch) {
COORD pos;
HANDLE output = GetStdHandle(STD_OUTPUT_HANDLE);
pos.X = x;
pos.Y = y;
SetConsoleCursorPosition(output, pos);
for (int i = 0; i < height; i++) {
cout << ch;
pos.Y++;
SetConsoleCursorPosition(output, pos);
}
}
void DrawWater(int x, int y, int width, char ch) {
COORD pos;
HANDLE output = GetStdHandle(STD_OUTPUT_HANDLE);
pos.X = x;
pos.Y = y;
SetConsoleCursorPosition(output, pos);
for (int i = 0; i < width; i++) {
cout << ch;
pos.X++;
SetConsoleCursorPosition(output, pos);
}
}
void Draw(vector<int>& height) {
int maxHeight = *max_element(height.begin(), height.end());
int minHeight = *min_element(height.begin(), height.end());
int screenTop = kScreenHeight - 1;
int screenBottom = 0;
for (int i = 0; i < height.size(); i++) {
int x = i * (kScreenWidth - 1) / (height.size() - 1);
int y = screenTop - (height[i] - minHeight) * (screenTop - screenBottom) / (maxHeight - minHeight);
DrawBar(x, y, kScreenHeight - y - 1, '#');
}
for (int i = 1; i < height.size() - 1; i++) {
int leftHeight = height[i];
for (int j = i - 1; j >= 0; j--) {
leftHeight = max(leftHeight, height[j]);
}
int rightHeight = height[i];
for (int j = i + 1; j < height.size(); j++) {
rightHeight = max(rightHeight, height[j]);
}
int water = min(leftHeight, rightHeight) - height[i];
if (water > 0) {
int x = i * (kScreenWidth - 1) / (height.size() - 1);
int y = screenTop - (min(leftHeight, rightHeight) - minHeight) * (screenTop - screenBottom) / (maxHeight - minHeight) - water;
DrawWater(x, y, 1, '~');
}
}
}
int main() {
vector<int> height = {0,1,0,2,1,0,1,3,2,1,2,1};
Draw(height);
return 0;
}
```
该程序使用了Windows API来控制控制台输出。首先,我们定义了`DrawBar`函数和`DrawWater`函数来分别绘制柱子和水。其中,`DrawBar`函数接受柱子的坐标`(x, y)`和高度`height`,使用循环输出字符来绘制柱子;`DrawWater`函数接受水的坐标`(x, y)`、长度`width`和字符`ch`,使用循环输出字符来绘制水。
接着,我们定义了`Draw`函数来绘制整个场景。该函数首先计算出最高柱子和最低柱子的高度,并将屏幕分成若干个区间。然后,对于每个柱子,根据其高度计算出在屏幕上的位置,并使用`DrawBar`函数绘制柱子。最后,对于每个柱子,计算它左边和右边的最高柱子高度,根据高度差计算出水的高度,并使用`DrawWater`函数绘制水。
最后,在`main`函数中定义了一个示例输入,调用`Draw`函数绘制出结果。
运行程序,可以看到绘制出了一个柱状图和水的效果,可以更好地理解接雨水问题的解法。