1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| class Solution { var cnt=0 fun movingCount(m: Int, n: Int, k: Int): Int { traceback(Array(n){BooleanArray(m){false}},0,0,m,n,k) return cnt } fun traceback(skip:Array<BooleanArray>,r:Int,c:Int,m:Int,n:Int,k:Int){ var sum=0 skip[r][c]=true
for(i in r.toString()){ sum+=i-'0' } for(i in c.toString()){ sum+=i-'0' }
if(sum<=k)cnt++ else return
if(r>0&&!skip[r-1][c]) traceback(skip,r-1, c, m,n,k) if(r<n-1&&!skip[r+1][c]) traceback(skip,r+1, c, m,n,k) if(c>0&&!skip[r][c-1]) traceback(skip, r, c-1, m, n, k) if(c<m-1&&!skip[r][c+1]) traceback(skip, r, c+1, m, n, k) } }
|