一、题目描述
一只蚂蚁坐在由白色和黑色方格构成的无限网格上。开始时,网格全白,蚂蚁面向右侧。每行走一步,蚂蚁执行以下操作。
(1) 如果在白色方格上,则翻转方格的颜色,向右(顺时针)转 90 度,并向前移动一个单位。
(2) 如果在黑色方格上,则翻转方格的颜色,向左(逆时针方向)转 90 度,并向前移动一个单位。
编写程序来模拟蚂蚁执行的前 K 个动作,并返回最终的网格。
网格由数组表示,每个元素是一个字符串,代表网格中的一行,黑色方格由 'X' 表示,白色方格由 '_' 表示,蚂蚁所在的位置由 'L', 'U', 'R', 'D' 表示,分别表示蚂蚁 左、上、右、下 的朝向。只需要返回能够包含蚂蚁走过的所有方格的最小矩形。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/langtons-ant-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
二、解题思路
关键是无限网格的处理,既然无限,显然不能预先给定尺寸,但动态网格,将面临副索引的问题,未解决副索引问题,使用双重索引字典构造自己的动态二维数组,实现动态网格。
三、代码实现
import numpy as np
class Solution:
def printKMoves(self, K: int) -> List[str]:
def helper(loc, op = 0):
loc_index = np.array(loc) + loc_op.get(direct_cell[op])
curr_marker = marker.get(tuple(loc_index), 1)
marker[tuple(loc_index)] = curr_marker * (-1)
direct = (op + curr_marker) % 4
return loc_index, direct
# if K == 0:
# return ['R']
color_map = {-1: 'X', 1: '_'}
marker = {}
direct = {}
direct_cell = ('R', 'D', 'L', 'U')
loc_op = {'R': [0, 1], 'D': [1, 0], 'L': [0, -1], 'U': [-1, 0]}
i = 0
op = 0
op_f = 0
loc = (0, 0)
# marker[loc] = 1
while i <= K:
op_f = op
loc, op = helper(loc, op)
i += 1
scope = [np.array([min(idx), max(idx)]) + [0, 1] for idx in list(zip(*marker.keys()))]
# print(loc)
marker[tuple(loc)] = 3
# print(marker)
res = [''.join([color_map.get(marker.get((i, j), 1), direct_cell[op_f]) for j in range(*scope[1])]) for i in range(*scope[0])]
return res
四、出现问题及结果
最初的代码,输入0,输出为[‘_R’](预期输出['R']),输入1,输出为[‘_X’,'_D'](预期输出['X', 'D']);看到输入1后的预期输出,才知道初始位置不被认为是蚂蚁去过的地方,需要排除原点。