Skip to content

Commit e65f15f

Browse files
authored
added solution for 212 (fishercoder1534#154)
1 parent 865429d commit e65f15f

File tree

1 file changed

+40
-0
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+40
-0
lines changed

src/main/java/com/fishercoder/solutions/_212.java

+40
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package com.fishercoder.solutions;
22

33
import java.util.ArrayList;
4+
import java.util.HashSet;
45
import java.util.List;
56

67
public class _212 {
@@ -68,4 +69,43 @@ private TrieNode buildTrie(String[] words) {
6869
return root;
6970
}
7071
}
72+
73+
public static class Solution2 {
74+
public List<String> findWords (char[][] board, String[] words) {
75+
76+
List<String> result = new ArrayList();
77+
HashSet<String> set = new HashSet();
78+
for (String word : words) {
79+
for (int i = 0; i < board.length; i++) {
80+
for (int j = 0; j < board[0].length; j++) {
81+
if (board[i][j] == word.charAt(0) && search(board, i, j, 0, word)) {
82+
set.add(word);
83+
}
84+
}
85+
}
86+
}
87+
result = new ArrayList<>(set);
88+
return result;
89+
}
90+
91+
private boolean search(char[][] board, int i, int j, int count, String word) {
92+
if (count == word.length()) {
93+
return true;
94+
}
95+
96+
if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || board[i][j] != word.charAt(count)) {
97+
return false;
98+
}
99+
100+
char temp = board[i][j];
101+
board[i][j] = ' ';
102+
103+
boolean foundWord = search(board, i + 1, j, count + 1, word)
104+
|| search(board, i - 1, j, count + 1, word)
105+
|| search(board, i, j + 1, count + 1, word)
106+
|| search(board, i, j - 1, count + 1, word);
107+
board[i][j] = temp;
108+
return foundWord;
109+
}
110+
}
71111
}

0 commit comments

Comments
 (0)