Reputation: 5302
I have this Matrix:
A B C
D E F
G H I
I want to get all possible combinations of adjacent cells and diagonal cells with a lenght of 3, for example:
Starting from A:
- *ABC* right right
- *ABE* right down
- *ABF* right diagonal-right
- *ABD* right diagonal-left
- ecc ecc
I tried to create a new class called "lettera", with as key the letter, and with a member that indicates the pointer to right, left, down, up ecc. And also with a member called "sequenza", a string that concatenate every letter it touch.
For example if a have as key, "B", i have B->down == *E, B->left == *A, B->right == *C and so on... And it works. Then I put a counter for each letter: when it arrives at 3 it should stop determinating combinations.
Then the core of the problem: the path for each letter to follow... I tried do create a recursive function, but it doenst work.
Can you please help me by watching this or by suggesting me another way?
Thanks a lot.
The code:
void decisione(lettera *c) {
if (c == nullptr) return ;
c->count++;
c->sequenza = c->sequenza + c->key;
if (c->count == 2)
cout << "\n" << c->sequenza;
//the sequence of letters accumulated in every call
decisione(c->Up);
decisione(c->Down);
}
It gives me for example AAA and BBB and then it crashes =(
Upvotes: 0
Views: 1301
Reputation: 689
Start at A, where can you go? B and D. Suppose you go to B, now, where can you go? A, C and E. You've already been in A and you don't want to return, so you only have C and E. Suppose you pick C, as you have already picked three letters the function stops and then you pick E and so on (I'm not choosing diagonal neighbors), here is the program:
#include <cstdio>
#include <cstdlib>
int a[] = {-1,-1,-1,0,0,1,1,1}, b[] = {-1,0,1,-1,1,-1,0,1},cont;
char s[3],mat[3][3];
bool flag[9];
void display() {
for(int i = 0; i < 3; ++i) printf("%c",s[i]);
puts("");
}
void show(int x,int y) {//You are in mat[x][y]
s[cont] = mat[x][y];
if(cont == 2) {
display();
return;
}
flag[mat[x][y] - 'A'] = true;
int xx,yy;
for(int i = 0; i < 8; ++i) {
xx = x + a[i], yy = y + b[i];
if(0 <= xx and xx < 3 and 0 <= yy and yy < 3 and !flag[mat[xx][yy] - 'A']) {
++cont;
show(xx,yy);
--cont;
}
}
flag[mat[x][y] - 'A'] = false;
}
int main() {
cont = 0;
for(int i = 0; i < 3; ++i) {
for(int j = 0; j < 3; ++j) {
mat[i][j] = ('A' + 3*i + j);
}
}
for(int i = 0; i < 3; ++i) {
for(int j = 0; j < 3; ++j) {
show(i,j); //You start from mat[i][j]: {'A','B','C',...,'I'}
}
}
return 0;
}
Upvotes: 1