Quantcast
Viewing all articles
Browse latest Browse all 14011

How do I solve this python Interview Question problem [closed]

The problem is an over simplification of the flow of liquid. - A terrain is given as a grid of cells of random elevations. The grid is always odd sized and is always a square - A liquid is poured at the central cell. Water can flow only north-south or east-west; not diagnonally. - At the first step, the water level is the same as the central cell - Water from one cell flows to a neighbouring cell if the level of water is equal to greater than the elevation of the neighbouring cell. - When the water flows to the neighbouring cell, the level of water is maintained. - If the water cannot flow to any new cell, the water level rises. - The simulation stops when the water reaches the end of the domain. The output consists of the domain represented by. and W representing dry and wet terrain.

Below is an example

Input Format

7 494 88 89 778 984 726 220 301 639 280 824 127 505 172 193 613 154 544 211 124 60 572 389 635 170 174 946 391 167 931 780 416 340 959 666 673 499 843 575 314 620 954 275 507 290 787

Note:First line of input has dimension n of(nXn) matrix.

I tried this,

def flow_ofLiquid(grid):  n = len(grid)  water_level = grid[n//2][n//2]  direction = [(0,1),(0,-1),(1,0),(-1,0)]def is_valid(x,y):  return 0 ,+x<n and 0 <=y<ndef canFlow(x,y,nx,ny):  return is_valid(nx,ny) and grid[nx][ny]<=water_leveldef flow(x,y):  nonlocal water_level  for dx,dy in direction:    nx,ny=x+dx,y+dy    if canFlow(x,y,nx,ny):      water_level = max(water_level, grid[nx][ny])      grid[nx][ny] = water_level      flow(nx,ny)flow(n//2,n//2)for i in range(n):  for j in range(n):    if grid[i][j]<water_level:      grid[i][j] = '.'return gridterrainSize = int(input("Enter grid size: "))terrain_grid = []for i in range(terrainSize):  row = list(map(int,input().split()))  terrain_grid.append(row)output = flow_ofLiquid(terrain_grid)for row in output:  print(''.join(map(str,row)))

Viewing all articles
Browse latest Browse all 14011

Trending Articles