Trapping Rain Water)

Source: Internet
Author: User

Question:


Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.

For example,
Given [,], return 6.

 


The above elevation map is represented by array [,]. In this case, 6 units of rain water (blue section) are being trapped.
Analysis: This question is indeed very interesting. My solution is to traverse each layer to find the number of rain.

For example, if the given array is [,], first traverse the array from both ends of the array and find the two endpoints that are not zero, they are the second and 12th positions respectively;

Next, traverse the array and calculate the number of rainwater captured at the first layer, so that the first layer can capture two units. Next, you can recursively solve each layer. When traversing the complete array, the algorithm will end.

Note: It seems that we are solving the problem by traversing each layer. In fact, the time complexity of the algorithm is O (N ).

The Code is as follows:

Int slove (int A [], int begin, int end)
{
If (end-begin <= 1) return 0;
While (A [begin] = 0) begin ++;
While (A [end] = 0) end --;
Int count = 0;
If (A [begin]> = A [end] & (end-begin> 1 ))
{
For (int I = begin + 1; I <end; I ++)
{
If (A [I] <A [end])
{
Count + = A [end]-A [I];
A [I] = 0;
}
Else
{
A [I]-= A [end];
}
}
A [begin]-= A [end];
A [end] = 0;
Count + = slove (A, begin, end-1 );
}
If (A [begin] <A [end] & (end-begin> 1 ))
{
For (int I = begin + 1; I <end; I ++)
{
If (A [I] <A [begin])
{
Count + = A [begin]-A [I];
A [I] = 0;
}
Else
{
A [I]-= A [begin];
}
}
A [end]-= A [begin];
A [begin] = 0;
Count + = slove (A, begin + 1, end );
}
Return count;
}
Int trap (int A [], int n ){
If (n <= 1) return 0;
Int result = slove (A, 0, n-1 );
Return result;
}

 

 

 


 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.