This commit is contained in:
Mrhongxing committed 2026-10-13 23:33:59 +08:00
1 parent 97f3b8d69e
commit 5d14218049
2 files changed
+90

No files matched your search

+83
View File
@@ -3,8 +3,91 @@ package com.hong.www;
import java.util.*; import java.util.*;
public class A212 { 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<String> 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<String> findWords(char[][] board, String[] words) { public List<String> findWords(char[][] board, String[] words) {
HashSet<String> 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<String> result = new ArrayList<>(); List<String> 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; 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<String> result = a212.findWords(board, words);
for (String x : result) {
System.out.println(x);
}
}
} }
+7
View File
@@ -0,0 +1,7 @@
package com.hong.www;
public class WordNode {
public WordNode[] nextChar=new WordNode[26];
public String word=null;
WordNode(){};
}