Delete space in pattern find
import java.util.*;
class PatternFind {
public static boolean search(int n, int m, char[][] words, String word) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (dfs(n, m, words, word, i, j, 0)) return true;
}
}
return false;
}
public static boolean dfs(int n, int m, char[][] words, String word, int i, int j, int k) {
if (k == word.length()) return true;
if (i < 0 || i >= n || j < 0 || j >= m || words[i][j] != word.charAt(k))
return false;
char temp = words[i][j];
words[i][j] = '#';
boolean found = dfs(n, m, words, word, i + 1, j, k + 1) ||
dfs(n, m, words, word, i - 1, j, k + 1) ||
dfs(n, m, words, word, i, j + 1, k + 1) ||
dfs(n, m, words, word, i, j - 1, k + 1);
words[i][j] = temp;
return found;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
char[][] words = new char[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
words[i][j] = sc.next().charAt(0);
}
}
sc.nextLine(); // clear leftover newline
String word = sc.nextLine().replaceAll("\\s+", ""); // remove spaces
boolean result = search(n, m, words, word);
System.out.println(result);
}
}
Comments
Post a Comment