diff --git a/src/com/hong/www/A212.java b/src/com/hong/www/A212.java index 0d92a13..6b4a247 100644 --- a/src/com/hong/www/A212.java +++ b/src/com/hong/www/A212.java @@ -3,8 +3,91 @@ package com.hong.www; import java.util.*; public class A212 { + public class WordNode { + public WordNode[] nextChar = new WordNode[26]; + public String word = null; + + WordNode() { + }; + } + + public void abs(WordNode Root, char[][] board, int i, int j, List result) { + if (board[i][j] == '#') { + return; + } + if (board[i][j] == '#') { + return; + } + if (Root.nextChar[board[i][j] - 'a'] != null) { + char temp = board[i][j]; + board[i][j] = '#'; + if (Root.nextChar[temp - 'a'].word != null) { + result.add(Root.nextChar[temp - 'a'].word); + } + // } else { + + if (i - 1 >= 0&&board[i-1][j]!='#') { + abs(Root.nextChar[temp - 'a'], board, i - 1, j, result); + } + if (j - 1 >= 0&&board[i][j-1]!='#') { + abs(Root.nextChar[temp - 'a'], board, i, j - 1, result); + } + if (i + 1 < board.length&&board[i+1][j]!='#') { + abs(Root.nextChar[temp - 'a'], board, i + 1, j, result); + } + if (j + 1 < board[0].length&&board[i][j+1]!='#') { + abs(Root.nextChar[temp - 'a'], board, i, j + 1, result); + } + board[i][j] = temp; + } + } + public List findWords(char[][] board, String[] words) { + HashSet temp = new HashSet<>(); + WordNode root = new WordNode(); + WordNode Root = root; + for (String x : words) { + char[] xx = x.toCharArray(); + root = Root; + for (int i = 0; i < xx.length; i++) { + /* + * if(root.nextChar[xx[i]-'a']!=null){ + * root + * } + */ + if (root.nextChar[xx[i] - 'a'] == null) { + root.nextChar[xx[i] - 'a'] = new WordNode(); + } + root = root.nextChar[xx[i] - 'a']; + if (i == xx.length - 1) { + root.word = x; + } + } + + } List result = new ArrayList<>(); + for (int i = 0; i < board.length; i++) { + for (int j = 0; j < board[0].length; j++) { + //char[][] boardtemp =new char[board.length][board[0].length]; + abs(Root, board, i, j, result); + } + } + for (String x : result) { + temp.add(x); + } + result.clear(); + result.addAll(temp); return result; } + + public static void main(String[] args) { + A212 a212 = new A212(); + char[][] board = { { 'o', 'a', 'b', 'n' }, { 'o', 't', 'a', 'e' }, { 'a', 'h', 'k', 'r' }, + { 'a', 'f', 'l', 'v' } }; + String[] words = { "oa", "oaa" }; + List result = a212.findWords(board, words); + for (String x : result) { + System.out.println(x); + } + } } diff --git a/src/com/hong/www/WordNode.java b/src/com/hong/www/WordNode.java new file mode 100644 index 0000000..bc852d0 --- /dev/null +++ b/src/com/hong/www/WordNode.java @@ -0,0 +1,7 @@ +package com.hong.www; + +public class WordNode { + public WordNode[] nextChar=new WordNode[26]; + public String word=null; + WordNode(){}; +}