Word Search II

本文介绍了一种算法,用于在给定的二维棋盘上查找所有可能的单词,每个单词由相邻的字母组成,且同一字母不能重复使用。

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"].

 

public class Solution {
	Set<String> res = new HashSet<String>();

	public List<String> findWords(char[][] board, String[] words) {
		Trie trie = new Trie();
		for (String word : words) {
			trie.insert(word);
		}

		int m = board.length;
		int n = board[0].length;
		boolean[][] visited = new boolean[m][n];
		for (int i = 0; i < m; i++) {
			for (int j = 0; j < n; j++) {
				dfs(board, visited, "", i, j, trie);
			}
		}

		return new ArrayList<String>(res);
	}

	public void dfs(char[][] board, boolean[][] visited, String str, int x,
			int y, Trie trie) {
		if (x < 0 || x >= board.length || y < 0 || y >= board[0].length)
			return;
		if (visited[x][y])
			return;

		str += board[x][y];
		if (!trie.startsWith(str))
			return;

		if (trie.search(str)) {
			res.add(str);
		}

		visited[x][y] = true;
		dfs(board, visited, str, x - 1, y, trie);
		dfs(board, visited, str, x + 1, y, trie);
		dfs(board, visited, str, x, y - 1, trie);
		dfs(board, visited, str, x, y + 1, trie);
		visited[x][y] = false;
	}
}

class TrieNode {

	private TrieNode[] nodes;
	private boolean end;

	public TrieNode() {
		int size = 26;
		nodes = new TrieNode[size];
		end = false;
	}

	public void insert(char[] chars, int start) {
		if (start == chars.length) {
			end = true;
			return;
		}
		int idx = chars[start] - 'a';
		TrieNode node = nodes[idx];
		if (node != null) {
			node.insert(chars, start + 1);
		} else {
			node = new TrieNode();
			nodes[chars[start] - 'a'] = node;
			node.insert(chars, start + 1);
		}
	}

	public boolean search(char[] chars, int start) {
		if (start == chars.length) {
			return end;
		}
		char c = chars[start];
		TrieNode node = nodes[c - 'a'];
		if (node == null) {
			return false;
		}
		return node.search(chars, start + 1);
	}

	public boolean startWith(char[] chars, int start) {
		if (start == chars.length) {
			return true;
		}
		char c = chars[start];
		TrieNode node = nodes[c - 'a'];
		if (node == null) {
			return false;
		}
		return node.startWith(chars, start + 1);
	}
}

class Trie {
	private TrieNode root;

	public Trie() {
		root = new TrieNode();
	}

	// Inserts a word into the trie.
	public void insert(String word) {
		root.insert(word.toCharArray(), 0);
	}

	// Returns if the word is in the trie.
	public boolean search(String word) {
		return root.search(word.toCharArray(), 0);
	}

	// Returns if there is any word in the trie
	// that starts with the given prefix.
	public boolean startsWith(String prefix) {
		return root.startWith(prefix.toCharArray(), 0);
	}
}

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值