Reputation: 4262
I have a 2d char array and I'm trying to find a specific character using recursion.
public class Test {
char arry [][] = {{'1',' ','B'},
{'C','K','M'},
{'H','R','P'}
};
public Test(){
recursion(0,0,arry[0][0]);
}
private void recursion(int row, int col, char c) {
if(c==' '){
System.out.print("Location: " + row + " " + col );
}else
{
if(col+1<arry[0].length){
recursion(row,col,c);
}
//System.out.print(arry[0][1]);
}
}
public static void main(String[] args) {
new Test();
}
}
but this is giving me a stack overflow. how can I find an element in a 2d array using recursion.
Upvotes: 0
Views: 14279
Reputation: 48733
The easiest way to search for a value in a 2D-Array would be to start at (0, 0) and scan through the entire column before advancing to the next row. When a value matches what you are looking for, return that location.
Here is an example.
import java.util.Arrays;
public class Find2D {
public static int[] search(char[][] arr, char ch, int row, int col) {
if (arr[row][col] == ch) {
return new int[] { row, col };
} else {
if (col + 1 < arr[0].length) {
return search(arr, ch, row, col + 1);
} else if (row + 1 < arr[1].length) {
return search(arr, ch, row + 1, 0);
}
}
return null;
}
public static int[] search(char[][] arr, char ch) {
return search(arr, ch, 0, 0);
}
public static void printr(int[] result) {
System.out.println("Location: " + Arrays.toString(result));
}
public static void main(String[] args) {
char arr[][] = {
{ '1', ' ', 'B' },
{ 'C', 'K', 'M' },
{ 'H', 'R', 'P' }
};
printr(search(arr, arr[0][0])); // [0, 0]
printr(search(arr, 'M')); // [1, 2]
printr(search(arr, 'x')); // null
}
}
Upvotes: 0
Reputation: 476
It looks like your if statement isn't being executed properly. You are checking to check if c == " "
, though I think you meant it to check if array[row][col]==c
. Also, it seems like you never actually increment the values of row
and col
, so the recursion continuously happens on itself. Since the recursion values never change, and the check can never be true, this will eventually lead to a stackoverflow.
Try something along these lines:
private void recursion(int row, int col, char c) {
if(array[row][col]==c){
System.out.print("Location: " + row + " " + col );
} else {
if(col+1<array[0].length){
recursion(row,col+1,c);
} else if(row + 1<array[1].length){
recursion(row+1,0,c);
} else {
System.out.print("Does not exist");
//System.out.print(arry[0][1]);
}
}
}
Upvotes: 1
Reputation: 675
private void recursion(int row, int col, char c) {
if(c==' '){
System.out.print("Location: " + row + " " + col );
}else
{
if(col+1<arry[0].length){
recursion(row,col+1,c);
}
else
recursion(row+1, 0, c)
//System.out.print(arry[0][1]);
}
}
Upvotes: 0
Reputation: 8657
You method is calling itself with same values all the time.
recursion(row,col,c);
Update your value then send it to the method again. so it could look for another element in your array
For example:
recursion(row,++col,c);
Upvotes: 0