leetcode 756. Pyramid Transition Matrix | 756. 金字塔转换矩阵(BFS)

x33g5p2x  于2021-11-30 转载在 其他  
字(0.8k)|赞(0)|评价(0)|浏览(273)

题目

https://leetcode.com/problems/pyramid-transition-matrix/

题解

BFS,把 pattern 用 map 存起来,然后 bfs 从下向上一层一层尝试每个 pattern 是否可行。注意状态的转移。

  1. class Solution {
  2. int N;
  3. Map<String, List<Character>> map;
  4. public boolean pyramidTransition(String bottom, List<String> allowed) {
  5. N = bottom.length();
  6. map = new HashMap<>();
  7. for (String s : allowed) {
  8. String k = s.substring(0, 2);
  9. List<Character> list = map.getOrDefault(k, new ArrayList<>());
  10. list.add(s.charAt(2));
  11. map.put(k, list);
  12. }
  13. char[][] arr = new char[N][N];
  14. for (int i = 0; i < N; i++) {
  15. arr[N - 1][i] = bottom.charAt(i);
  16. }
  17. return bfs(arr, N - 1, 0);
  18. }
  19. public boolean bfs(char[][] arr, int i, int j) {
  20. if (i == 0) return true;
  21. if (j == i) return bfs(arr, i - 1, 0);
  22. List<Character> list = map.get("" + arr[i][j] + arr[i][j + 1]);
  23. if (list == null) return false;
  24. for (Character c : list) {
  25. arr[i - 1][j] = c;
  26. if (bfs(arr, i, j + 1)) return true;
  27. }
  28. return false;
  29. }
  30. }

相关文章