There is a stack of water glasses in the form of a Pascal triangle and a person wants to pour the water at the topmost glass, but the capacity of each glass is 1 unit. Overflow occurs in such a way that after 1 unit, 1/2 of the remaining unit gets into the bottom left glass and the other half in the bottom right glass. We pour k units of water into the topmost glass. The task is to find how much water is there in the c'th glass of the r'th row.
Note: Assume that there are enough glasses inthe triangle till no glass overflows.
Example:
Input: k = 3, r = 2, c = 1 Output: 1.000000 Explanation: After the first glass, 2 units of water will remain and they will spread equally on the two glasses on the second row. Therefore, the glass on the 2nd row and 1st column will have 1 unit of water.
Input: k = 2, r = 2, c = 2 Output: 0.5 Explanation: After the first glass, 1 units of water will remain and they will spread equally on the two glasses on the second row. Therefore, the glass on the 2nd row and 2nd column will have half unit of water.
Using Dynamic Programming - O(r^2) time and O(r^2) Space
The approach to solving the water overflow problem involves simulating water distribution through a grid-based representation of a Pascal triangle of glasses. The process starts by pouring a given amount of water into the top glass. Then, for each glass, the algorithm checks if the water exceeds the glass's capacity of 1 unit. If overflow occurs, the excess water is evenly distributed to the two glasses directly below. Each glass is capped at a maximum of 1 unit. This process is repeated iteratively until the target row is reached. The final result is the amount of water in the specified glass, ensuring no glass exceeds its maximum capacity.
C++
// C++ program to find amount// of water in a given glass Using Dynamic Programming#include<bits/stdc++.h>usingnamespacestd;doublewaterOverflow(intk,intr,intc){// DP matrix to simulate water flow in glassesvector<vector<double>>memo(r,vector<double>(r,0.0));// Initial water in top glassmemo[0][0]=k;// Simulate water flow through trianglefor(introw=0;row<r-1;row++){for(intcol=0;col<=row;col++){// Calculate water overflowdoubleexcess=max(0.0,memo[row][col]-1.0);// Distribute excess waterif(excess>0){// Cap current glassmemo[row][col]=1.0;// Flow to bottom glassesmemo[row+1][col]+=excess/2.0;memo[row+1][col+1]+=excess/2.0;}}}// Return water in target glassreturnmin(1.0,memo[r-1][c-1]);}intmain(){intk=3;intr=2;intc=1;doublewaterAmount=waterOverflow(k,r,c);cout<<waterAmount<<endl;return0;}
Java
// Java program to find amount// of water in a given glass Using Dynamic Programmingimportjava.util.*;classGfG{staticdoublewaterOverflow(intk,intr,intc){// DP matrix to simulate water flow in glassesdouble[][]memo=newdouble[r][r];// Initial water in top glassmemo[0][0]=k;// Simulate water flow through trianglefor(introw=0;row<r-1;row++){for(intcol=0;col<=row;col++){// Calculate water overflowdoubleexcess=Math.max(0.0,memo[row][col]-1.0);// Distribute excess waterif(excess>0){// Cap current glassmemo[row][col]=1.0;// Flow to bottom glassesmemo[row+1][col]+=excess/2.0;memo[row+1][col+1]+=excess/2.0;}}}// Return water in target glassreturnMath.min(1.0,memo[r-1][c-1]);}publicstaticvoidmain(String[]args){intk=3;intr=2;intc=1;doublewaterAmount=waterOverflow(k,r,c);System.out.println(waterAmount);}}
Python
# Python program to find amount # of water in a given glass Using Dynamic ProgrammingdefwaterOverflow(k,r,c):# DP matrix to simulate water flow in glassesmemo=[[0.0for_inrange(r)]for_inrange(r)]# Initial water in top glassmemo[0][0]=k# Simulate water flow through triangleforrowinrange(r-1):forcolinrange(row+1):# Calculate water overflowexcess=max(0.0,memo[row][col]-1.0)# Distribute excess waterifexcess>0:# Cap current glassmemo[row][col]=1.0# Flow to bottom glassesmemo[row+1][col]+=excess/2.0memo[row+1][col+1]+=excess/2.0# Return water in target glassreturnmin(1.0,memo[r-1][c-1])if__name__=="__main__":k=3r=2c=1waterAmount=waterOverflow(k,r,c)print(waterAmount)
C#
// C# program to find amount// of water in a given glass Using Dynamic ProgrammingusingSystem;classGfG{staticdoublewaterOverflow(intk,intr,intc){// DP matrix to simulate water flow in glassesdouble[,]memo=newdouble[r,r];// Initial water in top glassmemo[0,0]=k;// Simulate water flow through trianglefor(introw=0;row<r-1;row++){for(intcol=0;col<=row;col++){// Calculate water overflowdoubleexcess=Math.Max(0.0,memo[row,col]-1.0);// Distribute excess waterif(excess>0){// Cap current glassmemo[row,col]=1.0;// Flow to bottom glassesmemo[row+1,col]+=excess/2.0;memo[row+1,col+1]+=excess/2.0;}}}// Return water in target glassreturnMath.Min(1.0,memo[r-1,c-1]);}staticvoidMain(string[]args){intk=3;intr=2;intc=1;doublewaterAmount=waterOverflow(k,r,c);Console.WriteLine(waterAmount);}}
JavaScript
// JavaScript program to find amount// of water in a given glass Using Dynamic ProgrammingfunctionwaterOverflow(k,r,c){// DP matrix to simulate water flow in glassesletmemo=Array.from({length:r},()=>Array(r).fill(0.0));// Initial water in top glassmemo[0][0]=k;// Simulate water flow through trianglefor(letrow=0;row<r-1;row++){for(letcol=0;col<=row;col++){// Calculate water overflowletexcess=Math.max(0.0,memo[row][col]-1.0);// Distribute excess waterif(excess>0){// Cap current glassmemo[row][col]=1.0;// Flow to bottom glassesmemo[row+1][col]+=excess/2.0;memo[row+1][col+1]+=excess/2.0;}}}// Return water in target glassreturnMath.min(1.0,memo[r-1][c-1]);}letk=3;letr=2;letc=1;console.log(waterOverflow(k,r,c));
Output
1
Using Queue - O(r^2) Time and O(r) Space
The approach simulates the water overflow process using a queue to track water distribution through a Pascal triangle of glasses. The algorithm processes glasses row by row, managing overflow by distributing excess water equally to the glasses below. It ensures that no glass exceeds its 1-unit capacity, using the queue to efficiently handle water amounts and overflow at each step. The water in each glass is updated progressively, and the target glass’s water amount is returned once the process reaches the specified row and column.
C++
// C++ program to find amount // of water in a given glass using queue#include<bits/stdc++.h>usingnamespacestd;doublewaterOverflow(intk,intr,intc){r--;c--;// Initialize queue with total water unitsqueue<double>q;q.push(1.0*k);// Variable to track overflow from previous glassesdoubleprev=0;// Simulate water flow row by rowfor(inti=0;i<=r;i++){// Process current row's glassesintsize=q.size();for(intj=0;j<size;j++){// Get current glass water amountdoublecurr=q.front();// Check if target glass is reachedif(i==r&&j==c)returnmin(curr,1.0);// Reduce water in current glasscurr--;q.pop();// Calculate and distribute overflowdoubleval=max(curr/2.0,0.0)+prev;q.push(val);// Track overflow for next iterationprev=max(0.0,curr/2.0);}// Add previous row's overflow to next rowq.push(prev);prev=0;}return0;}intmain(){intk=3;intr=2;intc=1;cout<<waterOverflow(k,r,c);return0;}
Java
// Java program to find amount // of water in a given glass using queueimportjava.util.*;classGfG{staticdoublewaterOverflow(intk,intr,intc){// Adjust row and column to 0-based indexingr--;c--;// Initialize queue with total water unitsQueue<Double>q=newLinkedList<>();q.add(1.0*k);// Variable to track overflow from// previous glassesdoubleprev=0;// Simulate water flow row by rowfor(inti=0;i<=r;i++){// Process current row's glassesintsize=q.size();for(intj=0;j<size;j++){// Get current glass water amountdoublecurr=q.poll();// Check if target glass is reachedif(i==r&&j==c)returnMath.min(curr,1.0);// Reduce water in current glasscurr--;// Calculate and distribute overflowdoubleval=Math.max(curr/2.0,0.0)+prev;q.add(val);// Track overflow for next iterationprev=Math.max(0.0,curr/2.0);}// Add previous row's overflow to next rowq.add(prev);prev=0;}return0;}publicstaticvoidmain(String[]args){intk=3;intr=2;intc=1;System.out.println(waterOverflow(k,r,c));}}
Python
# Python program to find amount # of water in a given glass using queuefromcollectionsimportdequedefwaterOverflow(k,r,c):# Adjust row and column to 0-based indexingr-=1c-=1# Initialize queue with total water unitsq=deque([1.0*k])# Variable to track overflow from previous glassesprev=0# Simulate water flow row by rowforiinrange(r+1):# Process current row's glassessize=len(q)forjinrange(size):# Get current glass water amountcurr=q.popleft()# Check if target glass is reachedifi==randj==c:returnmin(curr,1.0)# Reduce water in current glasscurr-=1# Calculate and distribute overflowval=max(curr/2.0,0.0)+prevq.append(val)# Track overflow for next iterationprev=max(0.0,curr/2.0)# Add previous row's overflow to next rowq.append(prev)prev=0return0if__name__=="__main__":k=3r=2c=1print(waterOverflow(k,r,c))
C#
// C# program to find amount // of water in a given glass using queueusingSystem;usingSystem.Collections.Generic;classGfG{staticdoublewaterOverflow(intk,intr,intc){// Adjust row and column to 0-based indexingr--;c--;// Initialize queue with total water unitsQueue<double>q=newQueue<double>();q.Enqueue(1.0*k);// Variable to track overflow from previous glassesdoubleprev=0;// Simulate water flow row by rowfor(inti=0;i<=r;i++){// Process current row's glassesintsize=q.Count;for(intj=0;j<size;j++){// Get current glass water amountdoublecurr=q.Dequeue();// Check if target glass is reachedif(i==r&&j==c)returnMath.Min(curr,1.0);// Reduce water in current glasscurr--;// Calculate and distribute overflowdoubleval=Math.Max(curr/2.0,0.0)+prev;q.Enqueue(val);// Track overflow for next iterationprev=Math.Max(0.0,curr/2.0);}// Add previous row's overflow to next rowq.Enqueue(prev);prev=0;}return0;}staticvoidMain(string[]args){intk=3;intr=2;intc=1;Console.WriteLine(waterOverflow(k,r,c));}}
JavaScript
// JavaScript program to find amount // of water in a given glass using queuefunctionwaterOverflow(k,r,c){// Adjust row and column to 0-based indexingr--;c--;// Initialize queue with total water unitsletq=[];q.push(1.0*k);// Variable to track overflow from previous glassesletprev=0;// Simulate water flow row by rowfor(leti=0;i<=r;i++){// Process current row's glassesletsize=q.length;for(letj=0;j<size;j++){// Get current glass water amountletcurr=q.shift();// Check if target glass is reachedif(i===r&&j===c)returnMath.min(curr,1.0);// Reduce water in current glasscurr--;// Calculate and distribute overflowletval=Math.max(curr/2.0,0.0)+prev;q.push(val);// Track overflow for next iterationprev=Math.max(0.0,curr/2.0);}// Add previous row's overflow to next rowq.push(prev);prev=0;}return0;}letk=3;letr=2;letc=1;console.log(waterOverflow(k,r,c));