that's my first question here, so I'm apologizing in advance if I didn't data-mined well enough and duplicate the question.
So I'm trying to create some sort of a game where at some point you have a matrix like this:
_ _ _ _ _ _ |_|_|h|h|h|h| |_|_|_|_|_|_| |_|#|#|#|_|_| |_|_|_|#|_|_| |_|h|_|_|_|_| |_|h|#|_|_|_| And I need a method that checks if there are "elements" made up only by 'h'-es and if it finds one, to change all chars from 'h' to something else like 'd' for example so it becomes:
_ _ _ _ _ _ |_|_|d|d|d|d| |_|_|_|_|_|_| |_|#|#|#|_|_| |_|_|_|#|_|_| |_|h|_|_|_|_| |_|h|#|_|_|_| While it shouldn't change the other 'h'-es, that touch '#'-s I can either use for-cycles to run through the whole matrix, or start directly from the element, as I have the arr[y][x] coordinates. Either way, I'm using recursion to check the neighbors, but how do I prevent the method from stepping in back to the previous element and oscillate between them until... StackOverflow occurs? So far this is where I am:
public class matrixRec { public static void main(String[] args) { char[][] matrix = { {' ',' ',' ',' ',' ',' '}, {' ','h','h','h','h',' '}, {' ',' ',' ',' ',' ',' '}, {' ',' ',' ','#','#',' '}, {' ','h',' ',' ','#','#'}, {' ','h','#',' ',' ',' '} }; System.out.println(elementChange(matrix, 1, 2)); } static boolean elementChange(char[][] matrix, int y, int x){ if (matrix[y][x] == ' '){ return true; } else if (matrix[y][x] == '#'){ return false; } else if (matrix[y][x] == 'h'){ return (elementChange(matrix, y, x-1) && elementChange(matrix, y, x+1)); } else { return false; } } } So is there a way I prevent infinite recursion, without changing the 'h'-es, until I am sure that they're all 'h'?
ArrayOutOfBoudsException. add some checks that you don't get out of the array's size, and this should be your terminate case