fork download
  1. import java.util.ArrayList;
  2. import java.util.List;
  3.  
  4. public class Main {
  5. public static int counter = 0;
  6. public static List<int[]> shortestPaths = new ArrayList<int[]>();
  7.  
  8. public static void permute(int[] arr, int startIndex) {
  9. int size = arr.length;
  10. if (arr.length == (startIndex + 1)) {
  11. /*System.out.print("Permutation " + counter + " is: ");
  12.   for (int i = 0; i < size; i++) {
  13.   if (i == (size - 1))
  14.   System.out.print(arr[i] + "\n\n");
  15.   else
  16.   System.out.print(arr[i] + ", ");
  17.   }*/
  18. shortestPaths.add(arr);
  19. counter++;
  20. } else {
  21. for (int i = startIndex; i < size; i++) {
  22. int[] tempArr = new int[arr.length];
  23. System.arraycopy(arr, 0, tempArr, 0, arr.length);
  24. int tmp = tempArr[i];
  25. tempArr[i] = tempArr[startIndex];
  26. tempArr[startIndex] = tmp;
  27. permute(tempArr, startIndex + 1);
  28. tempArr = null;
  29. }
  30. }
  31. }
  32.  
  33. public static void main(String[] args) {
  34. int[] arr = { 1, 2, 3 };
  35. permute(arr, 0);
  36. System.out.print("\n\n\n\n");
  37. for (int[] a : shortestPaths) {
  38. System.out.println(a[0] + ", " + a[1] + ", " + a[2] + "\n");
  39. }
  40. }
  41. }
  42.  
Success #stdin #stdout 0.07s 380224KB
stdin
Standard input is empty
stdout



1, 2, 3

1, 3, 2

2, 1, 3

2, 3, 1

3, 2, 1

3, 1, 2