```
class Solution(object):
def numberOfPatterns(self, m, n):
visited = {}
ret = [0]
self.dfsHelper(ret, visited, 0, m, n, -9)
return ret[0]
def dfsHelper(self, ret, visited, res, m, n, prev):
if m <= res <= n:
ret[0] += 1
if res == n:
return
for i in xrange(1, 10):
if i not in visited:
x, y, xp, yp = (i - 1) / 3, (i - 1) % 3, (prev - 1) / 3, (prev - 1) % 3
if (5 not in visited and abs(xp - x) == 2 and abs(yp - y) == 2) or ((yp == y and abs(xp - x) == 2) or (xp == x and abs(yp - y) == 2)) and (prev + i) / 2 not in visited:
continue
visited[i] = 1
self.dfsHelper(ret, visited, res + 1, m, n, i)
del visited[i]
```