【leetcode】1138. Alphabet Board Path

Topics are as follows:

On an alphabet board, we start at position (0, 0), corresponding to character board[0][0].

Here, board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"], as shown in the diagram below.

We may make the following moves:

  • 'U' moves our position up one row, if the position exists on the board;
  • 'D' moves our position down one row, if the position exists on the board;
  • 'L' moves our position left one column, if the position exists on the board;
  • 'R' moves our position right one column, if the position exists on the board;
  • '!' adds the character board[r][c] at our current position (r, c) to the answer.

(Here, the only positions that exist on the board are positions with letters on them.)

Return a sequence of moves that makes our answer equal to target in the minimum number of moves.  You may return any path that does so.

 

Example 1:

Input: target = "leet"
Output: "DDR!UURRR!!DDD!"

Example 2:

Input: target = "code"
Output: "RR!DDRR!UUL!R!"

 

Constraints:

  • 1 <= target.length <= 100
  • target consists only of English lowercase letters.

Outline of Solution: This problem is not difficult, the entire table is abstracted as a coordinate axis, for example, a coordinate (0,0), l is the coordinate (2,1), then the path from a to l is to the left and right directions moving time (x coordinate minus a l x coordinate), the direction of moving up and down twice (l minus a coordinate y coordinate). One thing to note here is the start or termination characters are z, because whether it is starting or arriving from z z, u must pass only from arriving, and can not be left via z.

code show as below:

class Solution(object):
    def alphabetBoardPath(self, target):
        """
        :type target: str
        :rtype: str
        """
        board =  ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"]
        dic = {}
        for i in range(len(board)):
            for j in range(len(board[i])):
                dic[board[i][j]] = (i,j)
        x,y = 0,0
        res = ''
        for i in target:
            x1,y1 = dic[i]
            #
            if i == 'z':
                v = y - y1
                if v > 0:
                    res += 'L' * v
                else:
                    res += 'R' * (-v)
                v = x - x1
                if v > 0:
                    res += 'U' * v
                else:
                    res += 'D' * (-v)
            else:
                v = x - x1
                if v > 0:
                    res += 'U' * v
                else:
                    res += 'D' * (-v)
                v = y - y1
                if v > 0:
                    res += 'L'*v
                else:
                    res += 'R' * (-v)
            res += '!'
            x,y = x1,y1
        return res

 

Guess you like

Origin www.cnblogs.com/seyjs/p/11303301.html