# Python3, O(n*m):
```lang-py
import random, collections, copy
def generate(n, _cache):
a = [0 for _ in range(n)]
s, v, p = 0, {*range(n)}, set()
cache = copy.deepcopy(_cache)
while 1:
if not v or p&v:
if len(set(a)) == len(a): return a, cache
a = [0 for _ in range(n)]
s, v = 0, {*range(n)}
p = set()
cache = copy.deepcopy(_cache)
continue
if s not in cache[(i:=random.choice([*(v - [{0},set()][bool(s)])]))]:
a[i] = s
cache[i].add(s)
s, v = i, v - {i}
else:
p.add(i)
def main(n, m):
while 1:
cache = collections.defaultdict(set)
result = []
for _ in range(m):
a, cache = generate(n, cache)
result.append(a)
yield result
```
[Try it online!](https://tio.run/##hVLRasMwDHxev0JPwx5uSSmDEciXhFC8WGkNiW0ct1sp/fZOtpts7WBLHhLrpDudZHcKe2s2b85fr3pw1gfw0ig7CGht32MbtDVjPLjTQmEHOzToZUBmBGxb2e6RlwsACRXUBXTWwxa0iSQ7yuENYVR@FOAooxBwfpmgi4ARA@OUkXgIjyorhejiD7vRE/6x1z3COgoB6A6MDXAE0nLPxxJSNAM9GhZJJedQVekoeQkew8EbkCIrTQV/NZ2e2PmvticwGpoMpOc/FznJmqDNAScrYzJD4imtZrqs8gJW7d7qFln9wo6whPpcXESSa@p3a3s28oZe3pSzm1o3saW7dii2kkpR9oMnHT9LOOvsB/sRZyaXSjRfpI0PUpu47SEt@m4V347nq0LGO3nog9JtiKvIuh5HisVx59k@jDxTZxdiZv151e6HmOlW0jk0ijac4ieNvbpB14HqU@OvAjZ88aC3LgpSfHJem8AMfgbqgF@/AA)