作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/knight-dialer/description/

题目描述

A chess knight can move as indicated in the chess diagram below:

.

This time, we place our chess knight on any numbered key of a phone pad (indicated above), and the knight makes N-1 hops. Each hop must be from one key to another numbered key.

Each time it lands on a key (including the initial placement of the knight), it presses the number of that key, pressing N digits total.

How many distinct numbers can you dial in this manner?

Since the answer may be large, output the answer modulo 10^9 + 7.

Example 1:

  1. Input: 1
  2. Output: 10

Example 2:

  1. Input: 2
  2. Output: 20

Example 3:

  1. Input: 3
  2. Output: 46

Note:

  1. 1 <= N <= 5000

题目大意

马的初始位置可以在拨号按键的任意位置,现在要让它走N - 1步,问这个马能产生出多少种不同的拨号号码?

解题方法

动态规划TLE

本周周赛第二题,卡了我好久啊!好气!

这个题本身肯定是动态规划题目,设置dp数组为当前步以每个按键结尾的状态数。所以我使用了一个4×3的二维数组,需要注意的是左下角和右下角的位置不可能到达,设置它的数值为0.状态转移方程很好求得,那就是把上一步可能存在的位置状态累加在一起就成了当前位置的状态数。

问题是会超时啊!甚至可能会超过内存限制!

先上一份很容易想到的,但是会超时TLE的代码:

时间复杂度是O(N),空间复杂度O(N).

  1. class Solution:
  2. def knightDialer(self, N):
  3. """
  4. :type N: int
  5. :rtype: int
  6. """
  7. self.ans = dict()
  8. self.ans[0] = 10
  9. board = [[1] * 3 for _ in range(4)]
  10. board[3][0] = board[3][3] = 0
  11. pre_dict = {(i, j) : self.prevMove(i, j) for i in range(4) for j in range(3)}
  12. for n in range(1, N):
  13. new_board = copy.deepcopy(board)
  14. for i in range(4):
  15. for j in range(3):
  16. cur_move = 0
  17. for x, y in pre_dict[(i, j)]:
  18. cur_move = (cur_move + board[x][y]) % (10 ** 9 + 7)
  19. new_board[i][j] = cur_move
  20. board = new_board
  21. return sum([board[i][j] for i in range(4) for j in range(3)]) % (10 ** 9 + 7)
  22. def prevMove(self, i, j):
  23. if (i, j) == (3, 0) or (i, j) == (3, 2):
  24. return []
  25. directions = [(-2, 1), (-1, 2), (1, 2), (2, 1), (2, -1), (1, -2), (-1, -2), (-2, -1)]
  26. res = []
  27. for d in directions:
  28. x, y = i + d[0], j + d[1]
  29. if 0 <= x < 4 and 0 <= y < 3 and (x, y) != (3, 0) and (x, y) != (3, 2):
  30. res.append((x, y))
  31. return res

在比赛的时候剩下的一个小时都在优化这个题,个人感觉这个题卡时间卡的有点太严了,上面这个做法应该是标准做法吧,通过不了,需要一些奇技淫巧才能通过。

空间换时间,利用对称性

这是我在比赛最后的时间通过的代码,把所有状态给初始化了,这样好处是可以不用在循环中不停地copy原来的棋盘状态了,同时利用了对称性,只需要求出4个位置(1,2,4,0)的状态,其余状态可以直接利用对称性得到。

还有一个优化的地方在于在每次的过程中进行取模!虽然取模运算是耗时的运算,但是数字很大的时候,大整数既占空间又占时间,所以取模!

经过上面的优化勉强通过了,真是不容易,我觉得这个题非常不友好,因为同样的Java代码可以不做任何优化就通过了。这个题在N很大的时候还会告诉我内存超了……简直了。。

时间复杂度是O(N),空间复杂度O(N).总时间1500ms。

  1. class Solution:
  2. def knightDialer(self, N):
  3. """
  4. :type N: int
  5. :rtype: int
  6. """
  7. self.ans = dict()
  8. self.ans[0] = 10
  9. board = [[[1] * 3 for _ in range(4)] for _ in range(N)]
  10. board[0][3][0] = board[0][3][2] = 0
  11. pre_dict = {(i, j) : self.prevMove(i, j) for i in range(4) for j in range(3)}
  12. for n in range(1, N):
  13. for i in range(2):
  14. cur_move = 0
  15. for x, y in pre_dict[(i, 0)]:
  16. cur_move += board[n - 1][x][y]
  17. board[n][i][0] = cur_move % (10 ** 9 + 7)
  18. cur_move = 0
  19. for x, y in pre_dict[(0, 1)]:
  20. cur_move += board[n - 1][x][y]
  21. board[n][0][1] = cur_move % (10 ** 9 + 7)
  22. cur_move = 0
  23. for x, y in pre_dict[(3, 1)]:
  24. cur_move += board[n - 1][x][y]
  25. board[n][3][1] = cur_move % (10 ** 9 + 7)
  26. board[n][4][0] = board[n][0][0]
  27. board[n][0][2] = board[n][0][0]
  28. board[n][5][1] = 0
  29. board[n][6][2] = board[n][7][0]
  30. board[n][8][1] = board[n][0][1]
  31. board[n][9][2] = board[n][0][2]
  32. board[n][3][0] = board[n][3][2] = 0
  33. return (board[N - 1][0][0] * 4 + board[N - 1][0][1] * 2 + board[N - 1][10][0] * 2 + board[N - 1][3][1] + board[N - 1][11][1]) % (10 ** 9 + 7)
  34. def prevMove(self, i, j):
  35. if (i, j) == (3, 0) or (i, j) == (3, 2):
  36. return []
  37. directions = [(-2, 1), (-1, 2), (1, 2), (2, 1), (2, -1), (1, -2), (-1, -2), (-2, -1)]
  38. res = []
  39. for d in directions:
  40. x, y = i + d[0], j + d[1]
  41. if 0 <= x < 4 and 0 <= y < 3 and (x, y) != (3, 0) and (x, y) != (3, 2):
  42. res.append((x, y))
  43. return res

优化空间复杂度

上面的做法我一直在想着优化时间复杂度,事实上,每个状态只和之前的状态有关,所以很容易想到优化空间复杂度。

使用10个变量,分别保存每个位置能取到的状态数,然后人为的把每个状态能通过其他的状态得到的代码给写出来就行了。

代码如下,真的很简洁,为什么我没有想到优化空间!!优化之后时间降到了264 ms,这个告诉我们,优化空间同样可以大规模地降低时间,如果DP问题超时的话,优先考虑空间!

时间复杂度是O(N),空间复杂度O(1).时间264 ms.

  1. class Solution:
  2. def knightDialer(self, N):
  3. """
  4. :type N: int
  5. :rtype: int
  6. """
  7. if N == 1: return 10
  8. x1 = x2 = x3 = x4 = x5 = x6 = x7 = x8 = x9 = x0 = 1
  9. MOD = 10 ** 9 + 7
  10. for i in range(N - 1):
  11. x1, x2, x3, x4, x5, x6, x7, x8, x9, x0 = (x6 + x8) % MOD,\
  12. (x7 + x9) % MOD, (x4 + x8) % MOD, (x3 + x9 + x0) % MOD, 0, (x1 + x7 + x0) % MOD,\
  13. (x2 + x6) % MOD, (x1 + x3) % MOD, (x2 + x4) % MOD, (x4 + x6) % MOD
  14. return (x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 + x0) % MOD

如果在上面的解法上再利用好对称性的话,可以把时间再次降低到160 ms。

时间复杂度是O(N),空间复杂度O(1).时间160 ms。

  1. class Solution:
  2. def knightDialer(self, N):
  3. """
  4. :type N: int
  5. :rtype: int
  6. """
  7. if N == 1: return 10
  8. x1 = x2 = x3 = x4 = x5 = x6 = x7 = x8 = x9 = x0 = 1
  9. MOD = 10 ** 9 + 7
  10. for i in range(N - 1):
  11. x1, x2, x4, x0 = (x6 + x8) % MOD, (x7 + x9) % MOD, (x3 + x9 + x0) % MOD, (x4 + x6) % MOD
  12. x3, x5, x6, x7, x8, x9 = x1, 0, x4, x1, x2, x1
  13. return (x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 + x0) % MOD

相似题目

688. Knight Probability in Chessboard

参考资料

https://leetcode.com/problems/knight-dialer/discuss/189252/O(logN)

日期

2018 年 11 月 4 日 —— 下雨的周日

【LeetCode】935. Knight Dialer 解题报告(Python)的更多相关文章

  1. [LeetCode] 935. Knight Dialer 骑士拨号器

    A chess knight can move as indicated in the chess diagram below:  .            This time, we place o ...

  2. LeetCode 935. Knight Dialer

    原题链接在这里:https://leetcode.com/problems/knight-dialer/ 题目: A chess knight can move as indicated in the ...

  3. 【LeetCode】120. Triangle 解题报告(Python)

    [LeetCode]120. Triangle 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址htt ...

  4. LeetCode 1 Two Sum 解题报告

    LeetCode 1 Two Sum 解题报告 偶然间听见leetcode这个平台,这里面题量也不是很多200多题,打算平时有空在研究生期间就刷完,跟跟多的练习算法的人进行交流思想,一定的ACM算法积 ...

  5. 【LeetCode】Permutations II 解题报告

    [题目] Given a collection of numbers that might contain duplicates, return all possible unique permuta ...

  6. 【LeetCode】Island Perimeter 解题报告

    [LeetCode]Island Perimeter 解题报告 [LeetCode] https://leetcode.com/problems/island-perimeter/ Total Acc ...

  7. 【LeetCode】01 Matrix 解题报告

    [LeetCode]01 Matrix 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/01-matrix/#/descripti ...

  8. 【LeetCode】Largest Number 解题报告

    [LeetCode]Largest Number 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/largest-number/# ...

  9. 【LeetCode】Gas Station 解题报告

    [LeetCode]Gas Station 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/gas-station/#/descr ...

随机推荐

  1. W10: Warning: Changing a readonly file使用vi/vim报错问题解决

    使用vi/vim编辑文件的时候出现W10: Warning: Changing a readonly file报错 解决方法: 一.强制保存退出 :wq! 二.ll 查询文件属主,使用属主赋予权限 c ...

  2. PHP-FPM运行状态的实时查看及监控详解

    https://www.jb51.net/article/97640.htm https://blog.csdn.net/Dr_cokiy/article/details/105580758

  3. SpringBoot整合Shiro 二:Shiro配置类

    环境搭建见上篇:SpringBoot整合Shiro 一:搭建环境 Shiro配置类配置 shiro的配置主要集中在 ShiroFilterFactoryBean 中 关于权限: anon:无需认证就可 ...

  4. 关于java中的安全管理器

    最近再查看java的源码的时候看见了这一类代码 final SecurityManager sm = System.getSecurityManager(); 想要了解这个是为了做什么,查看资料之后发 ...

  5. day03 Django目录结构与reques对象方法

    day03 Django目录结构与reques对象方法 今日内容概要 django主要目录结构 创建app注意事项(重点) djago小白必会三板斧 静态文件配置(登录功能) requeste对象方法 ...

  6. Spark(八)【广播变量和累加器】

    目录 一. 广播变量 使用 二. 累加器 使用 使用场景 自定义累加器 在spark程序中,当一个传递给Spark操作(例如map和reduce)的函数在远程节点上面运行时,Spark操作实际上操作的 ...

  7. 零基础学习java------day9------多态,抽象类,接口

    1. 多态 1.1  概述: 某一个事务,在不同环境下表现出来的不同状态 如:中国人可以是人的类型,中国人 p = new  中国人():同时中国人也是人类的一份,也可以把中国人称为人类,人类  d  ...

  8. 前端必须知道的 Nginx 知识

    Nginx一直跟我们息息相关,它既可以作为Web 服务器,也可以作为负载均衡服务器,具备高性能.高并发连接等. 1.负载均衡 当一个应用单位时间内访问量激增,服务器的带宽及性能受到影响, 影响大到自身 ...

  9. C语言time函数获取当前时间

    以前放了个链接,但是原作者把博文删了,这里放一个获取时间的代码,已经比较详细所以不做注释 #include<stdio.h> #include<time.h> #include ...

  10. spring-dm 一个简单的实例

    spring-dm2.0  运行环境,支持JSP页面 运行spring web 项目需要引用包