Description

Given a board which is a 2D matrix includes a-z and dictionary dict, find the largest collection of words on the board, the words can not overlap in the same position. return the size of largest collection.
  • The words in the dictionary are not repeated.
  • You can reuse the words in the dictionary.

Example

Example 1:

Input:
["abc","def","ghi"]
{"abc","defi","gh"}
Output:
3 Explanation:
we can get the largest collection`["abc", "defi", "gh"]`

Example 2:

Input:
["aaaa","aaaa","aaaa","aaaa"]
{"a"}
Output:
16
Explanation:
we can get the largest collection`["a", "a","a","a","a","a","a","a","a","a","a","a","a","a","a","a"] 思路:tire + dfs。
字典树用于前缀查找。
dfs用于搜索,
找到单词时搜索下一个单词
没有搜索到单词时,四方向遍历(回溯 + 标记)
//建立tire树的过程
class Trie {
TrieNode root; Trie() {
root = new TrieNode('0');
} public void insert(String word) {
if(word == null || word.length() == 0) {
return;
}
TrieNode node = root;
for(int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
if(node.children[ch - 'a'] == null) {
node.children[ch - 'a'] = new TrieNode(ch);
}
node = node.children[ch - 'a'];
}
node.isWord = true;
}
}
//tire的结点
class TrieNode {
char value;
boolean isWord;
TrieNode[] children; TrieNode(char v) {
value = v;
isWord = false;
children = new TrieNode[26];
}
} public class Solution {
/**
* @param board a list of lists of character
* @param words a list of string
* @return an integer
*/
public int boggleGame(char[][] board, String[] words) {
// Write your code here
Trie trie = new Trie();
for(String word : words) {
trie.insert(word);
} int m = board.length;
int n = board[0].length;
List<String> result = new ArrayList<>();
boolean[][] visited = new boolean[m][n];
List<String> path = new ArrayList<>();
findWords(result, board, visited, path, 0, 0, trie.root);
return result.size();
}
//从当前位置出发寻单词存不存在
public void findWords(List<String> result, char[][] board, boolean[][] visited, List<String> words, int x, int y, TrieNode root) { int m = board.length;
int n = board[0].length; for (int i = x; i < m; i++) {
for (int j = y; j < n; j++) {
List<List<Integer>> nextWordIndexes = new ArrayList<>();
List<Integer> path = new ArrayList<>();
getNextWords(nextWordIndexes, board, visited, path, i, j, root);
for (List<Integer> indexes : nextWordIndexes) {
String word = "";
for (int index : indexes) {
int row = index / n;
int col = index % n;
visited[row][col] = true;
word += board[row][col];
} words.add(word);
if (words.size() > result.size()) {
result.clear();
result.addAll(words);
}
findWords(result, board, visited, words, i, j, root);
for (int index : indexes) {
int row = index / n;
int col = index % n;
visited[row][col] = false;
}
words.remove(words.size() - 1);
}
}
y = 0;
}
} int []dx = {0, 1, 0, -1};
int []dy = {1, 0, -1, 0};
//dfs搜索查找单词
private void getNextWords(List<List<Integer>> words, char[][] board,
boolean[][] visited, List<Integer> path, int i, int j, TrieNode root) {
if(i < 0 | i >= board.length || j < 0 || j >= board[0].length
|| visited[i][j] == true || root.children[board[i][j] - 'a'] == null) {
return;
}
//找下一个单词
root = root.children[board[i][j] - 'a'];
if(root.isWord) {
List<Integer> newPath = new ArrayList<>(path);
newPath.add(i * board[0].length + j);
words.add(newPath);
return;
}
//回溯标记
visited[i][j] = true;
path.add(i * board[0].length + j);
for (int k = 0; k < 4; k ++) {
getNextWords(words, board, visited, path, i + dx[k], j + dy[k], root);
}
path.remove(path.size() - 1);
visited[i][j] = false;
}
}

  

Boggle Game的更多相关文章

  1. Programming Assignment 4: Boggle

    编程作业四 作业链接:Boggle & Checklist 我的代码:BoggleSolver.java 问题简介 Boggle 是一个文字游戏,有 16 个每面都有字母的骰子,开始随机将它们 ...

  2. uvalive 7299 Boggle

    Boggle is a game in which 16 dice with letters on each side are placed into a 4 × 4 grid. Players th ...

  3. Trie树 + DFS - CSU 1457 Boggle

    Boggle Problem's Link: http://acm.csu.edu.cn/OnlineJudge/problem.php?id=1457 Mean: 给定n个串,有m个询问. 每个询问 ...

  4. UVa - 11283 - PLAYING BOGGLE

    先上题目 Problem F PLAYING BOGGLE Boggle® is a classic word game played on a 4 by 4 grid of letters. The ...

  5. 《算法问题实战策略》 BOGGLE

    oj地址是韩国网站 连接比较慢 https://algospot.com/judge/problem/read/BOGGLE大意如下 输入输出 输入 URLPM XPRET GIAET XTNZY X ...

  6. GCPC 2013_A Boggle DFS+字典树 CSU 1457

    上周比赛的题目,由于那个B题被神编译器的优化功能给卡了,就没动过这个题,其实就是个字典树嘛.当然,由于要在Boggle矩阵里得到初始序列,我还一度有点虚,不知道是用BFS还是DFS,最后发现DFS要好 ...

  7. UVALive 7299 Boggle(深搜的姿势)

    一开始确实是我的锅,我把题意理解错了,以为是一个q周围没有q的时候才可以当时qu,其实是只要碰到q,他就是qu,所以我们也可以通过预处理的方式,把字典中的不满足qu连在一起的直接去掉. 后来的各种TI ...

  8. DFS csu1719 Boggle

    传送门:id=1719">点击打开链接 题意:真正的题意是,告诉你一些字符串.然后告诉你非常多个字符格子,问这些字符串是否能在字符格子中连起来,在格子中对角线也觉得是连在一起的.假设格 ...

  9. Coursera 算法二 week 4 Boggle

    这次的作业主要用到了单词查找树和深度优先搜索. 1.在深度优先搜索中,在当前层的递归调用前,将marked数组标记为true.当递归调用返回到当前层时,应将marked数组标记为false.这样既可以 ...

  10. 玲珑OJ 1082:XJT Loves Boggle(爆搜)

    http://www.ifrog.cc/acm/problem/1082 题意:给出的单词要在3*3矩阵里面相邻连续(相邻包括对角),如果不行就输出0,如果可行就输出对应长度的分数. 思路:爆搜,但是 ...

随机推荐

  1. Hystrix实现ThreadLocal上下文的传递 转

    springcloud微服务中, 服务间传输全局类参数,如session信息等. 一.问题背景 Hystrix有2个隔离策略:THREAD以及SEMAPHORE,当隔离策略为 THREAD 时,是没办 ...

  2. jmeter 获取总的线程数

    String threads="${__BeanShell(ctx.getThreadGroup().getNumThreads())}"; vars.put("thre ...

  3. LuoguP3069 【[USACO13JAN]牛的阵容Cow Lineup

    题目链接 看了看其他大佬的文章,为什么要控制右端呢 其实就是一个很简单的模拟队列趴... 难点就在于根据题意我们可以分析得一段合法区间内,不同种类个数不能超过k+2 哦当然,由于种类数范围过大,要对种 ...

  4. Java分布式唯一ID生成方案——比UUID效率更高的生成id工具类

    package com.xinyartech.erp.core.util; import java.lang.management.ManagementFactory; import java.net ...

  5. AnimationClip压缩-动画文件压缩

    动画压缩方法一.常用方法1. Rig->Animation Type:改为Generic2. Animations->Anim.Compression:Optimal二.高级方法1. 去掉 ...

  6. 灰度共生矩阵(Gray-level Co-occurrence Matrix,GLCM),矩阵的特征量

    又叫做灰度共现矩阵 Prerequisites 概念 计算方式 对于精度要求高且纹理细密的纹理分布,我们取像素间距为d=1d=1,以下是方向的说明: 我们来看,matlab内置工具箱中的灰度共生矩阵的 ...

  7. Java之路---Day13

    2019-10-28-22:40:14 目录 1.Instanceof关键字 2.Final关键字 2.1Final关键字修饰类 2.2Final关键字修饰成员方法 2.3Final关键字修饰局部变量 ...

  8. 用jQuery的offset()替代javascript的offset

    在项目中遇到了一个问题,获取某个块状元素的offsetTop和offsetLeft时候会出现问题,并不是相对浏览器的位置,而是相对于某一个块状元素的位置,具体参照元素也没找到,因为页面中没有设置pos ...

  9. IntelliJ IDEA重命名变量的问题

    当我尝试使用Shift+ F6或简单地使用Refactor => Rename重命名变量时,有时intellij不仅重命名我想要的那个,而且还重命名具有相同名称的所有其他变量(在其他文件中)以及 ...

  10. XenCenter安装VM

    XenServer是服务器"虚拟化系统".系统设置为Linux_x86-64即可安装XenServer 和VMware ESX/ESXi有点不同的是,XenServer 不能在Xe ...