I am trying to traverse 2d matrix given below row-wise:
s o e g h
f l p i e
f i c o n
d t p l m
d u p r i
Recursion method I am using is given below where initially i=0, j=0 and maxRow = 5, maxCol = 5
public void traversingMatrix(int i, int j) {
if (i >= maxRow || j >= maxCol) {
return;
}
traversingMatrix(i, j + 1);
traversingMatrix(i + 1, j);
}
Output I am getting is:
0 0
0 1
0 2
0 3
0 4
/* after this things get weird */
1 4
2 4
3 4
4 4
1 3
1 4
2 4
....
How can I fix this so that recursion is row-wise.
You are traversing the matrix as if it was a binary tree: for every element, you visit two sons, namely (i, j+1) and (i+1, j).
The starting node is (0, 0). On the first recursion level, you visit (0, 1) and (1, 0). On the second level, (0, 2), (1, 1), (1, 1) and (2, 0) [note the double visit]. On the third level, (0, 3), (1, 2), (2, 1), (1, 2), (2, 1), (1, 2), (2, 1) and (3, 0) [note the triple visits]. And so on. (The actual visits are not performed in this order.)
The fix:
From a node, go to the left; go down only for the first node of a row.
public void traversingMatrix(int i, int j) {
if (i >= maxRow || j >= maxCol) {
return;
}
traversingMatrix(i, j + 1);
if (j == 0) traversingMatrix(i + 1, j);
}