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;
}