I just threw everything I know about Java optimization out of the window. I have the following task:
Given a 2D array representing the playing field and position in the field, fill out another array with the number of steps a player can take to get to any other position in the field. The player can move up, down, left and right. For example, the first neighbors will be all 1, and the diagonals will be all 2.
For the first attempt, I tried a simple 4-way fill algorithm. It is terribly slow.
Secondly, I decided to get rid of recursion and use a simple queue. It worked beautifully and gave tremendous acceleration (very roughly 20x). Here is the code:
private void fillCounterArray(int[] counters, int position) {
Queue<Integer> queue = new ArrayDeque<Integer>(900);
int[] destination = board.getPossibleDestinations(position);
for (int i = 0; i < destination.length; i++) {
if (board.getBoard()[destination[i]] == Board.CLEAR) {
counters[destination[i]] = 1;
queue.add(destination[i]);
}
}
while (!queue.isEmpty()) {
int pos = queue.remove();
int steps = counters[pos];
destination = board.getPossibleDestinations(pos);
for (int i = 0; i < destination.length; i++) {
int dest = destination[i];
if (board.getBoard()[dest] == Board.CLEAR && (counters[dest] > steps + 1 || counters[dest] == 0)) {
counters[dest] = steps + 1;
queue.add(dest);
}
}
}
}
" " , int-pointer . int []. , , . ( , C-side:)):
private void fillCounterArray(int[] counters, int position) {
int[] queue = new int[900];
int head = 0;
int[] destination = board.getPossibleDestinations(position);
for (int i = 0; i < destination.length; i++) {
if (board.getBoard()[destination[i]] == Board.CLEAR) {
counters[destination[i]] = 1;
queue[head++] = dest[i];
}
}
while (head > 0) {
int pos = queue[--head];
int steps = counters[pos];
destination = board.getPossibleDestinations(pos);
for (int i = 0; i < destination.length; i++) {
int dest = destination[i];
if (board.getBoard()[dest] == Board.CLEAR && (counters[dest] > steps + 1 || counters[dest] == 0)) {
counters[dest] = steps + 1;
queue[head++] = dest;
}
}
}
}
" ", , , , . , . ?