class Solution {
public List<String> findWords(char[][] board, String[] words) {
List<String> res = new ArrayList<>();
TrieNode root = buildTrie(words);
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
dfs (board, i, j, root, res);
}
}
return res;
} public void dfs(char[][] board, int i, int j, TrieNode p, List<String> res) {
char c = board[i][j];
if (c == '#' || p.next[c - 'a'] == null) return;
p = p.next[c - 'a'];
if (p.word != null) { // found one
res.add(p.word);
p.word = null; // de-duplicate
} board[i][j] = '#';
if (i > 0) dfs(board, i - 1, j ,p, res);
if (j > 0) dfs(board, i, j - 1, p, res);
if (i < board.length - 1) dfs(board, i + 1, j, p, res);
if (j < board[0].length - 1) dfs(board, i, j + 1, p, res);
board[i][j] = c;
} public TrieNode buildTrie(String[] words) {
TrieNode root = new TrieNode();
for (String w : words) {
TrieNode p = root;
for (char c : w.toCharArray()) {
int i = c - 'a';
if (p.next[i] == null) p.next[i] = new TrieNode();
p = p.next[i];
}
p.word = w;
}
return root;
} class TrieNode {
TrieNode[] next = new TrieNode[26];
String word;
}
}

参考:https://leetcode.com/problems/word-search-ii/discuss/59780/Java-15ms-Easiest-Solution-(100.00)

leetcode212的更多相关文章

  1. [Swift]LeetCode212. 单词搜索 II | Word Search II

    Given a 2D board and a list of words from the dictionary, find all words in the board. Each word mus ...

  2. LeetCode212. Word Search II

    https://leetcode.com/problems/word-search-ii/description/ Given a 2D board and a list of words from ...

随机推荐

  1. 数据挖掘标准规范之CRISP-DM基础

    一.前言 每每提到数据挖掘,总有些人上来就是ETL.是算法.是数学模型,作为搞工程实施的我而言,很是头疼.其实作为数据挖掘的而言,算法只是其实现手段.是工具和实现手段而已,我们不是在创造算法(国外职业 ...

  2. ALGO-17_蓝桥杯_算法训练_乘积最大(DP)

    问题描述 今年是国际数学联盟确定的“——世界数学年”,又恰逢我国著名数学家华罗庚先生诞辰90周年.在华罗庚先生的家乡江苏金坛,组织了一场别开生面的数学智力竞赛的活动,你的一个好朋友XZ也有幸得以参加. ...

  3. 【转】SOA架构设计经验分享—架构、职责、数据一致性

      1.背景介绍       最近一段时间都在做系统分析和设计工作,面对的业务是典型的重量级企业应用方向.突然发现很多以往觉得很简单的问题变得没有想象的那么容易,最大的问题就 是职责如何分配.论系统架 ...

  4. mac下 python3 安装--有说明原电脑安装的文件在哪里

    https://www.cnblogs.com/meng1314-shuai/p/9031686.html 前言:mac系统自带python,不过以当前mac系统的最新版本为例,自带的python版本 ...

  5. scala 基本类型和操作

    Scala基本类型 Scala中的基本数据类型如下图:  (来源:Programming in scala) 从上表中可以看出,Scala的基本数据类型与Java中的基本数据类型是一一对应的,不同的是 ...

  6. [UE4]暂停游戏、退出游戏、游戏输入模式

    游戏主界面WB_Main蓝图 Set Game Paused:暂停游戏 Show Mouse Cursor:显示鼠标 Set Input Mode:设置游戏输入模式(游戏和UI).仅仅游戏.仅仅UI( ...

  7. PLSQL导出对象的表结构和表数据

    https://jingyan.baidu.com/article/fcb5aff78e6a48edab4a7146.html

  8. 从MediaStorehe和sd中删除媒体文件

    参考资料:http://www.sandersdenardi.com/querying-and-removing-media-from-android-mediastore/ 从媒体表中删除: pri ...

  9. sas基础系列(2)-时间差精度获取

    data a; interval='month'; start='14FEB2013'd; end='13MAR2013'd; months_default=intck(interval, start ...

  10. (转)C# WebApi 接口参数不再困惑:传参详解

    原文地址:https://www.cnblogs.com/landeanfen/p/5337072.html 本篇打算通过get.post.put.delete四种请求方式分别谈谈基础类型(包括int ...