原文:https://blog.csdn.net/whl_program/article/details/82431762
结果应该输出1.
思路:约瑟夫环问题
# coding:utf-8
def circle(n, m):
a = [None] * 1001
# 死亡人数
dead = 0
# 报数
count = 0
res = 0
# 将每个人的位置保存到a中
for i in range(1, n + 1):
a[i] = i
for i in range(1, 10000):
if i > n:
i = i % n
if a[i] == 0: # 表示此人已死,不计
continue
# 活着就记数
if a[i] > 0:
count += 1
# 到了该杀人的m点且不为最后一人
if m == count and dead != n - 1:
count = 0 # 新的一轮
a[i] = 0 # 死亡置0
dead += 1
# 只剩最后一人就输出到结果中,终止循环
elif m == count and dead == n - 1:
res = a[i]
break
return res
print circle(4, 1)
暂时没有思路
思路:可以参考leetcode 675.为高尔夫比赛砍树,遇到障碍就跳过去,这里我使用的是BFS来解。参考别人的答案。
# coding:utf-8
from collections import deque
class Solution(object):
'''
def cutOffTree(self, forest, start, end):
if not forest or not forest[0]:
return -1
# cut the tree in reverse order of tree's height
# treeList = []
# for i in xrange(len(forest)):
# for j in xrange(len(forest[0])):
# if forest[i][j] > 1:
# treeList.append([forest[i][j], [i, j]])
# treeList.sort()
totalSteps = self.minStep(forest, start, end)
# k = 0
# while k < len(treeList) - 1:
# step = self.minStep(forest, treeList[k][1], treeList[k + 1][1])
# if step == -1:
# return -1
# totalSteps += step
# k += 1
return totalSteps
'''
# 传入平面图,开始位置和结束位置
def minStep(self, forest, start, end):
directions = [(0, -1), (0, 1), (-1, 0), (1, 0)]
step = 0
m, n = len(forest), len(forest[0])
visited = [[False for x in xrange(n)] for _ in xrange(m)]
visited[start[0]][start[1]] = True
queue = deque()
queue.append(start)
while queue:
size = len(queue)
for i in xrange(size):
curr = queue.popleft()
if curr == end:
return step
for direction in directions:
nextRow = curr[0] + direction[0]
nextCol = curr[1] + direction[1]
# 需要判定当前点位是否出界,或者该点是否被访问,遇到障碍时(==1)跳过,不做处理。
if nextRow < 0 or nextRow >= m or nextCol < 0 or nextCol >= n or visited[nextRow][nextCol] or \
forest[nextRow][nextCol] == 1:
continue
queue.append([nextRow, nextCol])
visited[nextRow][nextCol] = True
step += 1
# here, it means we can never find the destination
return -1
s = Solution()
print s.minStep([[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]], [0,4], [4, 4])
leetcode原题需要上面的函数。