我正在尝试通过Leetcode解决此问题。 351. Android Unlock Patterns。但是经过大约5个小时的调试,我找不到该Bug。这是问题描述:
给出一个Android 3x3按键锁定屏幕以及两个整数m和n,其中1≤m≤n≤9,计算Android锁定屏幕,由最少m个按键和最多n个按键组成键。
有效格式的规则:
- 每个模式必须连接至少m个键,最多n键。
- 所有键必须是唯一的。
- 如果行在模式中连接两个连续的键通过任何其他键,其他键必须先前已在图案。不允许跳过未选择的键。
- 使用的键的顺序很重要。
说明:
| 1 | 2 | 3 | | 4 | 5 | 6 | | 7 | 8 | 9 |
无效动作:
4 - 1 - 3 - 6
第1-3行通过键2,而键2未在模式。无效动作:
4 - 1 - 9 - 2
第1-9行通过键5尚未在模式中选择。有效移动:
2 - 4 - 1 - 3 - 6
第1-3行有效,因为它通过了通过在模式中选择的键2有效移动:
6 - 5 - 4 - 1 - 9 - 2
第1-9行有效,因为它通过已在模式中选择的键5。
我使用回溯来解决此问题,因此我不能使用过于复杂的测试用例进行调试。我的代码在n = m =1
和n = m = 2
时可以通过,但是在n = m = 3
时失败。我的代码将输出304而不是320。
我知道锁定模式是对称的,也就是说,拐角处的点和边缘中间的点将具有相同的输出,因此,如果找到一个,则可以乘以四。最后,处理中心点。对于m = n = 3
,我什至尝试绘制每种可能的组合,我得到角点为31,中间点为35,中心点为40,所以总组合为31 * 4 + 35 * 4 + 40 = 304
。我检查并重画了几次,但仍然找不到丢失的16。
我还检查了该问题讨论部分的帖子。我觉得这些方法非常相似,但是我不知道为什么我的方法会失败。
这是我的代码
class Solution { // Every dot can to go. // 1 2 3 // 4 5 6 // 7 8 9 int[][] directions = new int[][] { {0}, {2, 4, 5, 6, 8}, {1, 3, 4, 5, 6, 7, 9}, {2, 4, 5, 6, 8}, {1, 2, 3, 5, 7, 8, 9}, {1, 2, 3, 4, 6, 7, 8, 9}, {1, 2, 3, 5, 7, 8, 9}, {2, 4, 5, 6, 8}, {1, 3, 4, 5, 6, 7, 9}, {2, 4, 5, 6, 8} }; int m, n; public int numberOfPatterns(int m, int n) { this.m = m; this.n = n; int res = 0; boolean[] visited = new boolean[10]; res += dfs(1, 1, 0, visited) * 4; res += dfs(2, 1, 0, visited) * 4; res += dfs(5, 1, 0, visited); return res; } public int dfs(int cur, int len, int tempRes, boolean[] visited) { if (len > n || visited[cur]) return tempRes; if (len >= m && len <= n) tempRes++; visited[cur] = true; for (Integer child: directions[cur]) { tempRes = dfs(child, len + 1, tempRes, visited); } visited[cur] = false; return tempRes; } }
所有帮助都将非常有用,非常感谢。
我正在尝试通过Leetcode解决此问题。 351. Android解锁模式。但是经过大约5个小时的调试,我找不到该Bug。这是问题的描述:给定一个Android 3x3密钥...
有效移动: