# [Python 2], <s>317</s> 300 bytes <!-- language-all: lang-python --> <pre><code>def f(w,h,B): A=[w*[2]for c in' '*h];p=w+h for x,y,c in B:A[y][x]=c<'0' for i in range(2*p): 	x,y,u,v=[[[(0,2*p+~i,1,0),(w+p+~i,h-1,0,-1)][i<w+p],(w-1,i-w,-1,0)][i<p],(i,0,0,1)][i<w] 	while w>x>=0<=y<h:u,v=[(-v,-u),(v,u),(u,v)][A[y][x]];x+=u;y+=v 	print[[y+w,2*p+~y][x<0],[w+p+~x,x][y<h]][w>x>=0], </code></pre> [Try it online!][TIO-k1pldefa] [Python 2]: https://docs.python.org/2/ [TIO-k1pldefa]: https://tio.run/##TVBdb4IwFH2WX3HeQLlkbQVFpSb6N2ofFiejyYLEKB8v@@vsAs4taW56PnruSavuXlxL1fcflxx50FBBx/nWw0GbZmGUza83nOFKH/6isLtKN2HhYWBb6mhQcNweTGdNa/U584U/qW5Qbu/l5yVQi4oTZ4P/QbU2xgSCmAy/HUkScwqacARFxJAiObfGZcxZVphyUUODMtID6dgl6Gmz3qwp3NcFzb7da5HpLiu2454gqil6cHxNw2SOXzyr2l0b6seuC3XtzaqbK@/GdGEz1RocmbBkxl4ttdZwqLVmWmGpP3K6JCiC/@bPCUFCiF9gRRAvoCbb6fTr@4fSP2Q9Lw@koIS/3xsLTRO@iqEgofgIKL4KyDVkDJlgBZVC8lwhxQZSYQ21gUoQY4kEag12s7CEWkJKyNTvfwA "Python 2 – Try It Online"