Следующий mcve демонстрирует рекурсивное получение соседей и их накопление в уникальные комбинации.Код задокументирован с комментариями:
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
class Ideone
{
private static final int SIZE = 7; //size of combo
private static int[][] directions = { //represents moving directions
{-1, 0}, //up
{ 0,-1}, //left
{ 0, 1}, //right
{ 1, 0} //down
};
public static void main (String[] args) throws java.lang.Exception
{
int[][] matrix = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
};
Set<String> comboSet = get7DigitCombo(matrix);
System.out.print(comboSet.size());
}
public static Set<String> get7DigitCombo(int[][] matrix)
{
Set<String> comboSet = new HashSet<>();
get7DigitCombo(1, 0, matrix, String.valueOf(matrix[1][0]), comboSet);
return comboSet;
}
//recursively get all neighbors. generate combos by appending each neighbor
//combo represents a single combination. combos accumulates combination
static void get7DigitCombo(int row, int col, int[][] matrix, String combo, Set<String> combos){
if(combo !=null && combo.length() == SIZE) { //when combo reached the right size, add it
//System.out.println(combo);
combos.add(combo);
return;
}
//get and iterate over all adjacent neighbors
for(int[] neighbor : getNeighbors(row, col, matrix)){
get7DigitCombo(neighbor[0], neighbor[1], matrix, combo+neighbor[2], combos);
}
}
//return list of adjacent neighbors. each neighbor is represented by
//int[3]: row, column, value
private static List<int[]> getNeighbors(int row, int col, int[][] matrix) {
List<int[]> neighbors = new ArrayList<>();
for(int[] dir : directions){
int newRow = row + dir[0] ; int newCol = col + dir[1];
if(isValidAddress(newRow, newCol, matrix)) {
neighbors.add( new int[]{newRow,newCol, matrix[newRow][newCol]});
}
}
return neighbors;
}
private static boolean isValidAddress(int row, int col, int[][] matrix) {
if(row < 0 || col < 0) return false;
if(row >= matrix.length || col >= matrix[row].length) return false;
return true;
}
}