Тестирую по разному, по советам из коментов, результат верный, валидатор не принимает😕
package com.javarush.task.task20.task2027;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/*
Кроссворд
*/
public class Solution {
public static void main(String[] args) {
int[][] crossword = new int[][]{
{'f', 'd', 'e', 'r', 'l', 'k'},
{'u', 's', 'a', 'm', 'e', 'o'},
{'l', 'n', 'g', 'r', 'o', 'v'},
{'m', 'l', 'p', 'r', 'r', 'h'},
{'p', 'o', 'e', 'e', 'j', 'j'}
};
detectAllWords(crossword, "home", "same");
/*
Ожидаемый результат
home - (5, 3) - (2, 0)
same - (1, 1) - (4, 1)
*/
}
public static List<Word> detectAllWords(int[][] crossword, String... words) {
List<Word> wordList = new ArrayList<>();
int[] di = new int[]{-1, -1, -1, 0, 1, 1, 1, 0};
int[] dj = new int[]{-1, 0, 1, 1, 1, 0, -1, -1};
for (String w : words) {
char[] word = w.toCharArray();
for (int i = 0; i < crossword.length; i++) {
for (int j = 0; j < crossword[i].length; j++) {
if ((char) crossword[i][j] == word[0]) {
if (word.length == 1) {
Word foundWord = new Word(w);
foundWord.setStartPoint(j, i);
foundWord.setEndPoint(j, i);
wordList.add(foundWord);
System.out.println(foundWord);
} else {
for (int y = 0; y < di.length; y++) {
boolean wordIsFound = true;
for (int x = 1; x < word.length; x++) {
if (i + di[y] * x < 0 || j + dj[y] * x < 0 || i + di[y] * x >= crossword.length ||
j + dj[y] * x > crossword.length || crossword[i + di[y] * x][j + dj[y] * x] != word[x])
wordIsFound = false;
else wordIsFound = true;
}
if (wordIsFound) {
Word foundWord = new Word(w);
foundWord.setStartPoint(j, i);
foundWord.setEndPoint(j + dj[y] * (w.length() - 1), i + di[y] * (w.length() - 1));
wordList.add(foundWord);
System.out.println(foundWord);
}
}
}}
}
}
}
System.out.println("wordList.size() = " + wordList.size());
return wordList;
}
public static class Word {
private String text;
private int startX;
private int startY;
private int endX;
private int endY;
public Word(String text) {
this.text = text;
}
public void setStartPoint(int i, int j) {
startX = i;
startY = j;
}
public void setEndPoint(int i, int j) {
endX = i;
endY = j;
}
@Override
public String toString() {
return String.format("%s - (%d, %d) - (%d, %d)", text, startX, startY, endX, endY);
}
}
}