Здесь я хочу использовать DFS для перемещения в двумерном массиве от крайнего левого столбца к крайнему правому столбцу, каждый элемент может перейти к своему верхнему правому элементу или правому элементу или нижнему правому элементу. Мне нужно записать каждый возможный путь. Например, здесь у меня есть:
1 2 3
4 5 6
7 8 9
Тогда возможными путями будут 123, 126, 153, 156, 159, 423, 426, 453, 456, 459, 486, 489, 753, 756, 759, 786, 789
Теперь моя идея проста:
public int findSolution(int[][] array) {
List<List<Integer>> availablePaths = new ArrayList<List<Integer>>();
for (int i = 0; i < array.length; i++) {
List<Integer> tempList = new ArrayList<Integer>();
dfs(array, availablePaths, tempList, 0, i);
}
int res = 0;
int min = Integer.MAX_VALUE;
for (List<Integer> path : availablePaths) {
min = Integer.MAX_VALUE;
for (Integer cur : path) {
if (cur < min) {
min = cur;
}
}
if (min > res) {
res = min;
}
}
return res;
}
public void dfs(int[][] array, List<List<Integer>> availablePaths, List<Integer> tempList, int curCol, int curRow) {
if (tempList.size() == array[0].length) {
availablePaths.add(new ArrayList<Integer>(tempList));
return;
}
tempList.add(array[curRow][curCol]);
int startRow;
int endRow;
// Next Column
if (curRow == 0) {
startRow = 0;
endRow = curRow+1;
} else if (curRow == array.length-1) {
startRow = curRow - 1;
endRow = curRow;
} else {
startRow = curRow - 1;
endRow = curRow + 1;
}
for (int i = startRow; i <= endRow; i++) {
dfs(array, availablePaths, tempList, curCol + 1, i);
tempList.remove(tempList.size()-1);
}
}
Однако, это не может работать из-за ArrayIndexOutOfBoundsException, поэтому я думаю, что мой код имеет неверное представление.
Может ли кто-нибудь дать решение для решения этой проблемы?