for i inrange(k): if step[i] == 0: if x - 1 >= 0: x -= 1 result += mat[x][y] else: result += mat[x][y] elif step[i] == 1: if y + 1 <= nn: y += 1 result += mat[x][y] else: result += mat[x][y] elif step[i] == 2: if x + 1 <= mm and y + 1 <= nn: x += 1 y += 1 result += mat[x][y] else: result += mat[x][y] elif step[i] == 3: if x + 1 <= mm: x += 1 result += mat[x][y] else: result += mat[x][y] elif step[i] == 4: if y - 1 >= 0: y -= 1 result += mat[x][y] else: result += mat[x][y] elif step[i] == 5: if x - 1 >= 0and y - 1 >= 0: x -= 1 y -= 1 result += mat[x][y] else: result += mat[x][y] print(''.join(result)) print(len(set(result)))