您的位置:首页 > 其它

Word Search II

2015-05-31 16:33 134 查看
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.

思路:

  回溯

我的代码:

ublic 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]
;
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;
}
}


View Code
学习之处:

思路很简单,就是回溯,但是有一点需要自己学习,由于会有重复的结果,所以在我的代码里面需要加入 if(!list.contains(word))的判断以确定是否添加到结果List里面,但是在别人代码里面是用的Set<String> res = new HashSet<String>(); 这样直接过滤掉了重复的结果,如此一来节约了不少时间,最后再用return new ArrayList<String>(res);将set转换成List,完工!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: