key
public class Graph {
public static void main(String[] args) {
int[][] graph = {
{0, 2, 0, 0},
{0, 0, 3, 0},
{1, 0, 0, 4},
{2, 2, 0, 0}
};
new Graph().dfs(graph, 3);
}
public void dfs(int[][] graph, int node) {
boolean[][] flag = new boolean[graph.length][graph.length];
int cnt = dfs(graph, flag, node, node);
System.out.println(cnt);
}
private int dfs(int[][] graph, boolean[][] flag, int start, int end) {
int cnt = 0;
int[] row = graph[start];
for (int i = 0; i < row.length; i++) {
if (row[i] != 0 && !flag[start][i]) {
if (i == end) {
cnt++;
} else {
flag[start][i] = true;
cnt += dfs(graph, flag, i, end);
flag[start][i] = false;
}
}
}
return cnt;
}
}