- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 47 lines of Python from the credited upstream file ccc23j5.py.
- The implementation keeps its working state in language-native values and containers.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45 6import sys7input = sys.stdin.readline8 9def good(x, y):10 return 0 <= x < r and 0 <= y < c11 12def search(start, cur, turn, dirn):13 if cur == length - 1:14 return 115 cnt = 016 cr = start[0]17 cc = start[1]18 cd = d[dirn]19 nr, nc = cr + cd[0], cc + cd[1]20 if good(nr, nc) and graph[nr][nc] == word[cur+1]:21 cnt += search([nr, nc], cur + 1, turn, dirn)22 if not turn:23 for turnD in [(dirn+2)%8, (dirn-2)%8]:24 nd = d[turnD]25 nr, nc = cr + nd[0], cc + nd[1]26 if good(nr, nc) and graph[nr][nc] == word[cur+1]:27 cnt += search([nr, nc], cur + 1, True, turnD)28 return cnt29 30d = [[-1, 0], [-1, 1], [0, 1], [1, 1], [1, 0], [1, -1], [0, -1], [-1, -1]]31 32word = input().strip()33length = len(word)34r, c = int(input()), int(input())35graph = [input().strip().split() for i in range(r)]36 37count = 038 39for i in range(r):40 for j in range(c):41 if graph[i][j] == word[0]:42 for k in range(8):43 dirn = d[k]44 nr, nc = i + dirn[0], j + dirn[1]45 if good(nr, nc) and graph[nr][nc] == word[1]:46 count += search([nr, nc], 1, False, k)47print(count)