212、Word Search II (Hard)

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

Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.

For example,
Given words = ["oath","pea","eat","rain"] and board =

[
  ['o','a','a','n'],
  ['e','t','a','e'],
  ['i','h','k','r'],
  ['i','f','l','v']
]

Return ["eat","oath"].

这个题是79题的变种,当时看到我的第一想法是无非就是从判断一个词变成判断多个词,怎么难度就变成Hard了?拿79题的代码简单改改一提交,果然超时了,一看测试用例我去真复杂。看来原来的思路是不能用了,但是新的思路又想不出来,只能看提示,发现是要用前缀树,但是还是一脸蒙逼,毫无头绪。只能上网查有关资料,看到前缀树的几个应用才大概明白了思路。总之这个题和79题个人感觉出的还是很不错的,能让人很好的理解递归和前缀树。代码如下(注意前缀树的构造和它在这个题的解决算法中的应用思路):

import java.util.ArrayList;
import java.util.List;

public class Test {

	public static void main(String[] args) {
		char[][] board = new char[][] { { 'o', 'a', 'a', 'n' },
				{ 'e', 't', 'a', 'e' }, { 'i', 'h', 'k', 'r' },
				{ 'i', 'f', 'l', 'v' } };
		String[] words = new String[] { "eat", "oath", "pea", "rain" };

		List<String> list = findWords(board, words);
		for (String s : list) {
			System.out.println(s);
		}
	}

	public static List<String> findWords(char[][] board, String[] words) {
		TreeNode temp = BuildTree(words);
		List<String> list = new ArrayList<>();
		for (int i = 0; i < board.length; i++) {
			for (int j = 0; j < board[0].length; j++) {
				findBackTracking(board, i, j, temp, list);
			}
		}
		
		return list;
	}

	public static TreeNode BuildTree(String[] words) {
		TreeNode root = new TreeNode();
		for (int i = 0; i < words.length; i++) {
			TreeNode temp = root;
			char[] a = words[i].toCharArray();
			for (char c : a) {
				if (temp.next[c - 'a'] == null) {
					temp.next[c - 'a'] = new TreeNode();
				}
				temp = temp.next[c - 'a'];
			}
			temp.word = words[i];
		}
		return root;
	}

	public static void findBackTracking(char[][] board, int x, int y,
			TreeNode root, List<String> list) {

		char c = board[x][y];
		if (c == '$' || root.next[c - 'a'] == null) {
			return;
		}

		root = root.next[c - 'a'];
		if (root.word != null) {
			list.add(root.word);
			root.word = null;
		}

		board[x][y] = '$';
		if (x > 0)
			findBackTracking(board, x - 1, y, root, list);
		if (x < board.length - 1)
			findBackTracking(board, x + 1, y, root, list);
		if (y > 0)
			findBackTracking(board, x, y - 1, root, list);
		if (y < board[0].length - 1)
			findBackTracking(board, x, y + 1, root, list);
		board[x][y] = c;
	}
}

class TreeNode {
	String word;
	TreeNode[] next = new TreeNode[26];
}






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值