题目
909. 蛇梯棋
思路
完全不会!呜呜呜,看了别人的题解。二维数组之字形遍历放在一维数组里面,然后借助队列对数组进行bfs。
代码
class Solution {int n;int[] nums;public int snakesAndLadders(int[][] board) {// 暴力遍历n = board.length;// +1 是为了和方格对齐nums = new int[n*n + 1];// 借助标志isRight来之字形遍历二维数组 放在1维数组中boolean isRight = true;int idx = 1;for(int i = n - 1; i >= 0; i--){for(int j = (isRight? 0: n-1); isRight? j < n: j>= 0; j += isRight? 1: -1){nums[idx ++] = board[i][j];}isRight = !isRight;}int ans = bfs();return ans;}private int bfs(){Deque<Integer> queue = new LinkedList<>();Map<Integer, Integer> map = new HashMap<>();queue.addLast(1);// 初始化 在方格1 需要走0步map.put(1, 0);while(!queue.isEmpty()){int poll = queue.pollFirst();int step = map.get(poll);// 走到终点 返回步数if(poll == n*n) return step;for(int i = 1; i <= 6; i++){int np = poll + i;// 无效步数if(np <= 0 || np > n*n) continue;// 出现蛇或者梯子if(nums[np] != -1) np = nums[np];// 该步已经走过了if(map.containsKey(np)) continue;// 记录走到该位置需要的步数map.put(np, step+1);// 添加到队列中 可以作为下一阶段的起点queue.addLast(np);}}return -1;}
}
题目
208. 实现 Trie (前缀树)
思路
不知道前缀树应该是个什么样子的,去看了题解。主要有两个属性:isEnd用于标记当前字符是否为结束字符;Trie[]用于保存下一个可能出现的所有字符连接;
代码
class Trie {// 标记当前字符是否为结束字符private boolean isEnd;// 保存了对当前结点而言 下一个可能出现的所有字符的链接private Trie[] children;public Trie() {children = new Trie[26];isEnd = false;}public void insert(String word) {Trie node = this;for(int i = 0; i < word.length(); i++){char ch = word.charAt(i);// 计算当前字符对应的下标int index = ch - 'a';// 原来的树中没有这个前缀 if(node.children[index] == null){node.children[index] = new Trie();}// 继续创建该单词的后续字符node = node.children[index];}node.isEnd = true;}public boolean search(String word) {// 找得到且当前node是结束节点Trie node = searchPrefix(word);return node != null && node.isEnd;}public boolean startsWith(String prefix) {Trie node = searchPrefix(prefix);return node != null ;}public Trie searchPrefix(String prefix){// 如果找得到返回node 找不到返回nullTrie node = this;for(int i = 0; i < prefix.length(); i++){char ch = prefix.charAt(i);int index = ch - 'a';if(node.children[index] == null){return null;}node = node.children[index];}return node;}
}