JAVA - How to encode Node neighbors in a grid?

I am new to programming and as a school task I need to implement BFS, DFS and A * search algorithms in Java to search for a given target from a given starting position in a grid of a given size, 4x4, 8x8, etc.

For starters, I don’t know how to encode the neighbors of all nodes. For example, in an 8x8 grid, grid 1 has 2 and 9 as neighbors, and tile 12 has 4, 11, 13 and 20 as its neighbors, but I'm struggling to encode it. I need a part of the neighbors so that I can fly from the initial position to other parts of the support, moving horizontally or vertically through the neighbors.

 1  2  3  4  5  6  7  8 
 9 10 11 12 13 14 15 16 
17 18 19 20 21 22 23 24 
25 26 27 28 29 30 31 32 
33 34 35 36 37 38 39 40 
41 42 43 44 45 46 47 48 
49 50 51 52 53 54 55 56 
57 58 59 60 61 62 63 64

my node class:

class Node {
   int value;
   LinkedList<Node> neighbors;
   bool expanded;
}

Let's say they gave me an 8x8 grid correctly, so if I ran a program with an 8x8 grid to the right:

1 - my main method will create an array of List nodes, e.g. node

ArrayList<Node> test = new ArrayList<Node>();

1 64 ( 88).

- node, - , .

+3
2

, Node M N. nodes[r][c] Node r c ( ), List<Node> neighbors, .

:

for (int r = 0; r < M; r++) {
  for (int c = 0; c < N; c++) {
    Node n = nodes[r][c];
    List<Node> neighbors = n.neighbors;
    if (r > 0) {     // has north
      neighbors.add(nodes[r-1][c]);
    }
    if (r < M - 1) { // has south
      neighbors.add(nodes[r+1][c]);
    }
    if (c > 0) {     // has west
      neighbors.add(nodes[r][c-1]);
    }
    if (c < N - 1) { // has east
      neighbors.add(nodes[r][c+1]);
    }
  }
}

my main ArrayList<Node>

, - -. 1-D , nodes[r][c] nodeAt(r, c) :

Node nodeAt(int r, int c) {
   return nodesList.get(r * N + c);
}

1-D ( ).

+2

.

north = currentPos - gridSize;
east = currentPos + 1;
south = currentPos + gridSize;
west = currentPos - 1;

, ;)

+2

Source: https://habr.com/ru/post/1742038/


All Articles