I find a new way to traverse the quartet neighbors by using complex number in this solution.
https://leetcode.com/problems/word-search-ii/discuss/59804/27-lines-uses-complex-numbers
(you can just read my example.)
I think it is elegant and concise, but I can not fully understand about it.
Here I have extracted the key code, and simplify the exmaple.
board
is a 2d array, and we want to start from every node, and traverse the 4 direction neigbor recursively by dfs:
this is a common way:
def dfs(i, j, word):
# create 4 direction by hand
for I, J in (i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1):
# need to check boundary
if 0 <= I < len(board) and 0 <= J < len(board[0]):
dfs(I, J, word + c)
for i, j in board:
dfs(i, j, '')
here is using complex number as index:
board = {i + 1j * j: c
for i, row in enumerate(board)
for j, c in enumerate(row)}
def dfs(z, word):
c = board.get(z)
# here is visit 4 direction neighbors, which I don't understand
if c:
for k in range(4):
search(node[c], z + 1j ** k, word + c)
for z in board:
dfs(z, '')
I think there is two advantages by using complex number:
But I can't understand here for k in range(4): dfs(z + 1j ** k, word + c)
can somebody explain this algorithm? really appreciate it.
If what I think is correct this solution uses the following property of the imaginary number j
:
which if added to a complex number as a representation of a grid are the nodes: right, up, left, down
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.