0

I am trying to solve a recursive backtracking problem in which we must start at a given coordinate in a 2D array of ints, and find a path to an edge cell of the array, such that each successive element along the path is less than or equal to the previous one (starting with the given element) I don't know how to backtrack properly if the element in the current cell is equal to the previous element, so I have only been using test cases with different values in each cell. Any help / comments would be appreciated Here is my code so far:

public static boolean canFlowOffMap(int[][] map, int row, int col) {
    int current = map[row][col];
    return mthd6(map, current, row, col, false);
}

private static int[][] OPTIONS = { { 0, 1 }, { 0, -1 }, { 1, 0 }, { -1, 0 } };

private static boolean mthd6(int[][] map, int current, int r, int c, boolean result) {
    if (r == 0 || c == 0 || r == map.length -1 || c == map[0].length -1) {
        return true;
    } else {
        for (int[] option : OPTIONS) {
            r += option[0];
            c += option[1];
            if (map[r][c] < current) {
                current = map[r][c];
                result = mthd6(map, current, r, c, false);
            }
            r -= option[0];
            c -= option[1];
        }
        return result; 
    }
}
Flinch95
  • 1
  • 2
  • You can use [Breadth First Search](https://en.wikipedia.org/wiki/Breadth-first_search) to find the shortest path, if any. For more help please post [mre] and include hard coded test data. – c0der Jan 04 '20 at 15:56
  • You should have result = result || mthd6(... and there is no need to pass the variables current (which can be figured out using map, r and c) and result (which you always send as false). Provide some examples so we can test run your code. – Stefan Jan 05 '20 at 12:15

1 Answers1

0

See my comment above, and add a map that keeps track of the points you've already visited (since there is no point of going there again).

private static boolean mthd6(int[][] map, int r, int c, List<Point> visited) {
  int current = map[row][col];
  visited.add(new Point(r, c));
  if (r == 0 || c == 0 || r == map.length -1 || c == map[0].length -1) {
    return true;
  } else {
    for (int[] option : OPTIONS) {
        r += option[0];
        c += option[1];
        if (!visited.contains(new Point(r, c) && map[r][c] <= current) {
            result = result || mthd6(map, r, c);
        }
        r -= option[0];
        c -= option[1];
    }
    return result; 
  }
}
Stefan
  • 2,395
  • 4
  • 15
  • 32