755. Pour Water
Medium
We are given an elevation map,
heights[i]
representing the height of the terrain at that index. The width at each index is 1. After V
units of water fall at index K
, how much water is at each index?
Water first drops at index
K
and rests on top of the highest terrain or water at that index. Then, it flows according to the following rules:
We can assume there's infinitely high terrain on the two sides out of bounds of the array. Also, there could not be partial water being spread out evenly on more than 1 grid block - each unit of water has to be in exactly one block.
airbnb还要求把水滴过程给打印出来,也不难,写了个过程,看代码。主要是增加了一个全局的water数组来track哪些地方有水滴,有几滴。
/****************************************************************************** Online C++ Compiler. Code, Compile, Run and Debug C++ program online. Write your code in this editor and press "Run" button to compile and execute it. *******************************************************************************/ #include <iostream> #include <vector> using namespace std; class Solution { vector<int> water; vector<int> heights; int pos, drops, len; public: Solution(vector<int> h, int V, int K) { heights = h; drops = V; pos = K; len = 0; water.resize(h.size(), 0); } void pourWater() { if (heights.empty()) return; for (int i = 0; i<drops; i++) { int j = pos; while(j > 0 && heights[j-1]+water[j-1] <= heights[j] + water[j]) j--; while(j < heights.size()-1 && heights[j+1] + water[j+1] <= heights[j] + water[j]) j++; while(j > pos && heights[j-1] + water[j-1] <= heights[j] + water[j]) j--; water[j]++; print(); } } void print() { for (int i = 0; i<heights.size(); i++) { if (heights[i]+water[i] > len) len = heights[i]+water[i]; } vector<int> tmp = water; for (int i = 0; i<len; i++) { for (int j = 0; j<heights.size();j++) { if (tmp[j] > 0 && tmp[j]+heights[j] > len-i-1) { cout << 'W'; tmp[j]--; continue; } if (heights[j] > len-i-1) { cout << 'X'; continue; } cout << ' '; } cout << endl; } cout<<endl; } }; int main() { cout<<"Hello World" << endl; vector<int> heights = {2,1,1,2,1,2,2}; int V = 4; int K = 3; Solution sol(heights, V, K); sol.print(); sol.pourWater(); return 0; }
No comments:
Post a Comment