6

I have a 1 dimensional list of values, it looks like this "int[] values'". I beleive I have converted it to a 2d list like this :

for (int i = 0; i < 4; i++) {
    for (int j = 0; j < 4; j++) {
        board[i][j] = values[i * 4 + j];
    }
}

The board is the new 2 dimensional list of values. On the board there are numbers. A 0 means an empty space, a 1 is a green, a 2 is a blue, and a 3 is a red. How would I use depth first search to find a completed path of a certain color?

Claus
  • 150
  • 8
user2835532
  • 113
  • 1
  • 1
  • 10
  • 1
    Describe the algorithm you would use in English first .. then worry about converting that description to Java. (Homework question, so no code) – ErstwhileIII Mar 16 '14 at 23:52

1 Answers1

3
  • Make a 2D array boolean[][] visited designating the points that you have visited; set all elements to false
  • Go through each point in two nested loops
  • For each point where visited[r][c] is false, go into a DFS which you can implement recursively
  • Inside the recursive DFS call check if the point is your destination; if yes, return true
  • If the point has the correct color, explore its neighbors (up to four) in four directions
  • If a neighbor has the right color, mark it as visited, and make a recursive call
  • If a recursive call returns true, return true
  • Otherwise, continue exploring other neighbors
  • Once you are done exploring neighbors, return false.
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Alright thank you, this makes sense. But I guess I should have been more specific in my question, but I'm not too sure on how to actually do a dfs on the array. Is like a regular one? Or does it need to be modified since its on an array? – user2835532 Mar 17 '14 at 11:54
  • 3
    @user2835532 Think of an array as of an implicit representation of a graph. Each element is a vertex, with up to four edges connecting it to its neighbors (corners have two edges; sides have three edges; cells in the middle have all four). This gives you a complete representation of a graph. – Sergey Kalinichenko Mar 17 '14 at 12:20