Grid Walk with Obstacles
Python
Hard
3 views
Problem Description
You have a grid of size r x c. Start at (sr, sc). You get a command string of U, D, L, R. If a move goes outside grid, ignore it and count it as blocked. Output final position and blocked count.
Input Format
Line1: r c. Line2: sr sc. Line3: commands.
Output Format
One line: finalR finalC blocked.
Official Solution
import sys
lines=sys.stdin.read().splitlines()
if len(lines)<3:
sys.exit(0)
r,c=map(int,lines[0].split())
sr,sc=map(int,lines[1].split())
cmd=lines[2].strip()
rr=sr
cc=sc
blocked=0
for ch in cmd:
nr=rr
nc=cc
if ch=='U':
nr-=1
elif ch=='D':
nr+=1
elif ch=='L':
nc-=1
elif ch=='R':
nc+=1
if 0<=nr<r and 0<=nc<c:
rr=nr
cc=nc
else:
blocked+=1
sys.stdout.write(f'{rr} {cc} {blocked}')
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!