简体   繁体   中英

use complex number to traverse neighbors in 2d array

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:

  1. don't need to create 4 direction by hand
  2. don't need to check boundary

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 : j ^ 1,j ^ 2,j ^ 3,j ^ 4 = j,-1,-j,1

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM