[Question]
  [
# Drunkard's Journey Home
In this challenge you are to write a program which simulates a drunkard stumbling his way home from the bar.
### Input:
The input will be an adjacency matrix (representing a directed graph) which represents paths the drunkard can take. At each location, the drunkard will choose one path at random (Each option has an approximately equal chance and is independent of prior choices) to follow.
Assume that the drunkard always starts at the bar (first row in the adjacency matrix).
If the drunkard enters a dead-end it can be assumed that he has either made his way home or has been arrested for public intoxication and the program should return his path.
It can be assumed that the graph will always contain at least one dead-end.
It can also be assumed that the drunkard will always be able to exit the bar (the first row will not be all zeroes) and that if the drunkard would be stuck in a location, that the row would be represented by all zeroes.
### Output:
The output will be the path the drunkard took in his attempt to make his way home. The values for the locations can be either zero or one indexed.
### Examples:
```
Input
[1,0,1,1]
[0,0,0,0]
[1,0,0,0]
[1,1,1,1]
Possible Outputs
[0,2,0,3,2,0,0,3,1]
[0,3,0,3,1]
Input
[0,1,1,1,0,1]
[1,0,1,0,1,1]
[0,0,0,0,0,0]
[0,0,0,0,0,1]
[1,0,0,0,0,0]
[0,0,0,0,0,0]
Possible outputs
[0,1,5]
[0,5]
[0,1,4,0,2]
[0,3,5]
[0,3,0,1,4,0,5]
Deterministic path:
Input
[0,0,1,0]
[0,0,0,1]
[0,1,0,0]
[0,0,0,0]
Output
[0,2,1,3]
```
  
[Answer]
## Mathematica, 72 bytes
```
{1}//.{r___,x_}:>{r,x,n=1;Check[RandomChoice[#[[x]]->(n++&/@#)],##&[]]}&
```
This is a function takes the matrix as an argument and returns a list, and it uses 1-indexing.
The basic idea is to start with
```
{1}//.
```
which repeatedly applies the rule that follows to the list `{1}` until it stops changing. The rule matches the pattern
```
{r___,x_}:>
```
which means "a list with zero or more elements called `r` followed by an element called `x`." This gives `x` as the last element in the current list, and we replace the list with
```
{r,x,<stuff>}
```
which is the original list with `<stuff>` appended. The stuff in question is
```
RandomChoice[#[[x]]->(n++&/@#)]
```
which takes `#[[x]]` (the `x`th element of the input matrix) as a list of weights and maps them to `n++&/@#`, which is short for `Range@Length@#` (i.e. `{1,2,3,...}` with the appropriate length). This will throw an error if the weights are all zero, which is why it's wrapped in a
```
Check[...,##&[]]
```
which will return `##&[]` if an error message is generated. This is just a fancy way of writing `Sequence[]`, which acts as a "nothing" element (`{1,2,Sequence[],3}` evaluates to `{1,2,3}`) and therefore leaves the list unchanged, causing the `//.` to stop replacing.
[Answer]
# [R](https://www.r-project.org/), ~~72~~ ~~69~~ 66 bytes
```
function(m,o=1)while({print(o);any(x<-m[o,])})o=sample(which(x),1)
```
[Try it online!](https://tio.run/##TYoxCoQwFAWvot1/8AUDdqsnEYsQDAY2@RIjZlk8e9Rm2WZmionFVn1T7B5MchLIswwKx@LeM33X6EIiwUuHD@W@8aPwhBMybNqv93F/ZqEMViiWvE7RZaprQ4pbVvyw/aufwR13QLkA "R – Try It Online")
Takes input as a `logical` matrix, and prints the 1-based indices to the console.
[Answer]
# [Perl 5](https://www.perl.org/) `-a0`, ~~53~~ 51 bytes
Give input matrix as separate tight strings on STDIN
```
$!/usr/bin/perl -a0
$n=!say$%;$F[$%]=~s:1:($%)=@-if 1>rand++$n:eg&&redo
```
[Try it online!](https://tio.run/##K0gtyjH9/18lz1axOLFSRdVaxS1aRTXWtq7YytBKQ0VV09ZBNzNNwdCuKDEvRVtbJc8qNV1NrSg1Jf//fwNDQ0MDQy4gBrK4DAyAtAEXiABSYNKAywBC/csvKMnMzyv@r2uQ@F/X11TP0EDPAAA "Perl 5 – Try It Online")
Damages `@F` during the loop body but it gets repaired by `redo`
[Answer]
# [MATL](https://github.com/lmendo/MATL),15 bytes
```
1`GyY)ft?th1ZrT
```
Output is 1-based.
Try it online! [First input](https://tio.run/##y00syfn/3zDBvTJSM63EviTDMKoo5P//aEMdBQMdBSBpaA1iQJG1giEqG4piAQ). [Second input](https://tio.run/##y00syfn/3zDBvTJSM63EviTDMKoo5P//aAMdBUMYArGtYQwYCRQx0EFFGCJwXXjUGMQCAA). [Third input](https://tio.run/##y00syfn/3zDBvTJSM63EviTDMKoo5P//aAMdBSAyBJLWChA2iGsNE0QVN4gFAA). 
### Explanation
```
1          % Push 1: initial value of current row index
`          % Do...while
  G        %   Push input matrix
  y        %   Duplicate from below: pushes copy of current row index
  Y)       %   Get that row
  f        %   Find: push (possibly empty) array of indices of non-zero entries
  t        %   Duplicate
  ?        %   If non-empty
    th     %     Attach a copy of itself. This is needed in case the array
           %     contains a single number n, because then the randsample
           %     function would incorrectly treat that as the array [1 2 ... n]
    1Zr    %     Randsample: pick 1 entry at random with uniform probability
    T      %     Push true
           %   End (implicit)
           % End (implicit). Proceed with a new iteration if the top of the
           % stack is truthy. This happens if the current row had some
           % non-zero entry, in which case true was pushed (and is now
           % consumed). If the current row was all zeros, the top of the stack
           % is an empty array that was produced by the find function, which is
           % falsy (and is also consumed now). In that case the loop is exited,
           % and then the stack contains a collection of numbers which
           % collectively describe the path
           % Implicit display
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 38 bytes
```
{0,{.[$^l].grep(?*,:k).roll}...^!*.kv}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/2kCnWi9aJS4nVi@9KLVAw15LxypbU68oPyenVk9PL05RSy@7rPZ/cWKlQpqGSrymQlp@ERenRrShjoGOoY5hrE60gQ4YAlmGSCwwjNXUAak1gPBAOqCqMHRD9SF4hgjzMOQM4OaCTYLLQcwzRFUfq/kfAA "Perl 6 – Try It Online")
[Answer]
# Python, 136 bytes
Using zero indexing, assuming randrange has been imported. Takes an input m as the adjacency matrix
**113 no imports**
`s=lambda m,c=0,p=[0],x=0:1 in m[c]and(m[c][x]and s(m,x,p+[x],randrange(len(m)))or s(m,c,p,randrange(len(m))))or p`
**136 with imports**
`import random as r;s=lambda m,c=0,p=[0],x=0:1 in m[c]and(m[c][x]and s(m,x,p+[x],r.randrange(len(m)))or s(m,c,p,r.randrange(len(m))))or p`
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~70 67~~ 65 bytes
```
f=->m,i=0{m[i].sum<1?[]:m[i][x=rand(m.size)]<1?f[m,i]:[x]+f[m,x]}
```
Thanks to [benj2240](https://codegolf.stackexchange.com/users/77973/benj2240) for saving 2 bytes!
[Try it online!](https://tio.run/##KypNqvyfZhsDxLp2uTqZtgbVudGZsXrFpbk2hvbRsVYgXnSFbVFiXopGrl5xZlWqZixQJi0aqDjWKroiVhvErIit/c9VoJAWHR1tqGOgY6hjGKvDpQAC0QY6YAjnG2LwwTA2NpbrPwA "Ruby – Try It Online")
[Answer]
# JavaScript (ES6), 87 bytes
```
f=(a,y=0)=>[y,.../1/.test(r=a[y])?f(a,(g=_=>r[k=Math.random()*r.length|0]?k:g())()):[]]
```
[Try it online!](https://tio.run/##fZBBCsIwEEX3PUWWiYxpojsh9QSeIAQb2rRGayJpEArevbaKlmKRmc0fPu9/5qzvui2CvcW186Xp@0pgDZ1gRGSyA0ppylMaTRtxEFp2iuyrwYBrcRRZkBdx0PFEg3alv2KyCrQxro6nB1P7y67GhAy7k0r1hXetbwxtfI0rLBOEJAcGHLiCUTB4zVvwuXiNShShZ29dDjlJkgUeextH6oRZCpnY04HPkpcc7H8DlKYIlyaacLXOttEW6Db8Bq0zxGAzdNiSD4/P4d9y/Cd2Ftk/AQ "JavaScript (Node.js) – Try It Online")
---
# Alternate version, 81 bytes
Takes input as an array of binary strings. The maximum supported size is 16x16.
```
f=(a,y=0)=>[y,...+(r=a[y])?f(a,(g=_=>+r[k=Math.random()*r.length|0]?k:g())()):[]]
```
[Try it online!](https://tio.run/##fY9BCsIwEEX3PUV2TTSNie6EtCfwBCFoaNOaWhNJg1Dw7jUqpRbE4S8@M8z7M626q7705hYy6yo91jwKKjxwinguBkwIWUPPlRgkKuo4gQ0/8nztxYUfVDgTr2zlrhCtPOm0bcL5QWVx2TcQoai9kHIsne1dp0nnGlhDkQCQMspYil@Oxvo4NrtYaSIRaZ2xJ3xCSfKDERERM@0uiRPpbdnMX/Tp/wyw2QBY6aD91VjTB1OCW/wYZDmgeIsZ3qEPis3Q6QT2HbSIGZ8 "JavaScript (Node.js) – Try It Online")
[Answer]
# Java 10, 135 bytes
```
m->{var R="0 ";for(int r=0,c,t;;R+=(r=c)+" "){t=0;for(int x:m[r])t+=x;if(t<1)return R;for(t=c=m.length;m[r][c*=Math.random()]<1;)c=t;}}
```
0-indexed
**Explanation:**
[Try it online.](https://tio.run/##jVPLboMwELz3K1ac7IYgfI3rSD32kKhKj1EOrkNap2Ais6SpEN9OjSFNaUlVmYe83t2ZYYe9PMrpfvvWqFQWBSykNtUNgDaY2J1UCSzbLcATWm1eQBF3st6sN5BR7g5qd7urQIlawRIMCGiy6bw6SgsrEcQQ8F1u2yqwIg5ViJyvJoJYoegkgIBWKOKvlNMsW9sNxYk4cb0jeMeoTbC0BlY@B4USWZQm5gVfeZu6VrdiIfE1stJs84zQzR3jVAnkdd3wjtyhfE4duZ7jMddbyJxM0klyUiTtNGJSIDHJO/QauyhAxcI4ZCGrw3MgDv26BNjvgF@139f@W/0BEHfZLcyw5zXkIdglyH5RupYZ/5uaZ/GzxYASGwUZAvjHec5asJiDnk7n7kX7umsURgYwMoKRIfwcw5nM0LTeEB77Yu3e8x8FJlmUlxgdnFUwNSR4MIcSZ863/Lug1kQwc4U9zkjl3v1oUYk6je6tlR9FhHlnQCJp32wM7zEvCv2cJuCiA@SRZBMpkv3RrBdfN58)
```
m->{                   // Method with integer-matrix parameter and String return-type
  var R="0 ";          //  Result-String, starting at "0 "
  for(int r=0,         //  Row-integer, starting at 0
          c,           //  Column-integer
          t;           //  Temp-integer
      ;                //  Loop indefinitely
       R+=             //    After every iteration: Append the result with:
          (r=c)+" "){  //     The current column and a delimiter-space,
                       //     And set the current row to this column at the same time
    t=0;               //   (Re-)set `t` to 0
    for(int x:m[r])    //   Loop over the values of the current row
      t+=x;            //    And add them to `t`
    if(t<1)            //   If the entire row only contained zeroes:
      return R;        //    Return the result
    for(t=c=m.length;  //   Set `t` (and `c`) to the size of the matrix
        m[r][c*=Math.random()]<1;)
                       //   Loop until we've found a 1,
                       //   picking a random column in the range [0,`c`)
      c=t;}}           //    Reset the range of `c` to `t` (the size of the matrix)
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~123~~ 118 bytes
```
import System.Random
i#m|sum(m!!i)<1=pure[]|1<2=do{x<-randomRIO(0,length m-1);[i#m,x#m>>=pure.(x:)]!!(m!!i!!x)}
f=(0#)
```
[Try it online!](https://tio.run/##bY29DoIwFIX3PsVtWGhSSOuolN3JBMemAwmgjdxCSkkw4rMjqYuD59tOzs@9nh5t32@bxXHwAa7PKbSYV7VrBiQ2wXWaMUVKLSukGmffarPK4qCa4bUUmY@56nxJBe9bdwt3wEyyk96bfEmwLGMnT5cjM5TGIUoX9iadSkXCNuvGOSitJRdccmk4ga@04JEfR/5xIsYQgrV1oKCDuAj7MYzeurB9AA "Haskell – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 32 ~~34~~ bytes
```
t←⎕
{}{s[?≢s←⍸⍵⊃t]}⍣{~0∊t⊃⍨⎕←⍵}1
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97X/Jo7YJj/qmclXXVhdH2z/qXFQMEujd8ah366Ou5pLY2ke9i6vrDB51dJUA@Y96VwAVg1VsrTUEmfA/jetR22QTBZNHvVsMFQwUDBVAJAQawmkw5HrUOxdsHQnq0Z2F7ggk90FdXPuoa5EhAA "APL (Dyalog Unicode) – Try It Online")
Takes a nested binary array as input. Outputs each iteration on separate lines.
[Answer]
# [Python](https://docs.python.org), ~~97~~ 94 bytes
```
f=lambda a,i=0,j=0:sum(a[i])and[i]*a[i][j]+f(a[:],(i,j)[a[i][j]],id(a)**7%~-2**67%len(a))or[i]
```
[Try it online!](https://tio.run/##bYxBCsIwEEXX9hTZCEkcJVFQKPQkYRaRtjilTUtbhW68ek1iLShmJvl5fz7TTeOtdad5LrPaNtfcMguUKagylQ73hltDKKzLvcjwNxXuSu@mCJygEmYxESjnVkh52T73RynPl21dOO@ItveJmZqu7Uc2TENStj2ryRWMXODDMObk0oT50/XkRl7y4mFrHjJCiM1sjAamgPlXIzCjIoUOpH9pacTE@KiO5RXBRI03kIK1vuiT/DdTy9a4Z528t@nvNOIL "Python 3 – Try It Online")
---
See [this answer](https://codegolf.stackexchange.com/a/160171/20064) for more explanation about the random number generator:
```
id(a)**7%~-2**67
```
]