-
recursion again!!
I didn't get any responses from my last posting,so I'm assuming my code is too confusing, but I am desperate for help on this assignment. I have to create every possible combination of words
from a 2dimensional array of characters. We can go in 8 directions
N,NE,E,SE,S,SW,W,NW. My problem is remembering where i have been before, and we have to use a recursive function. I am only getting some of the possibilities, so I think my visited function is wrong.
-
visited and beenthere
to hard for me and this forum, good luck
-
This is a very enlightening problem, so I'll give you a start and let you go from there. I just wrote this up to print every combination of characters in any word and the number of total combinations, it should give you a very good idea of where to start. This is one of the simpler methods, but simple is good, right? :)
Code:
#include <iostream>
#include <string>
using namespace std;
void recurse ( char a[], int index )
{
char temp;
if ( a[index + 1] != '\0' ) {
temp = a[index];
a[index] = a[index + 1];
a[index + 1] = temp;
cout<< a <<endl;
recurse ( a, ++index );
}
return;
}
int main ( void )
{
unsigned i, index = 0;
char string[] = "weird";
size_t len = strlen ( string );
for ( i = 0; i < len; i++ )
recurse ( string, index );
cout<<"Total combinations: "<<(len * (len - 1))<<endl;
return EXIT_SUCCESS;
}
-Prelude
-
I think your problem is with diplaying results.
Here's a fix.
#include<iostream>
using namespace std;
enum visits{nv,v};
void CleartheGrid(visits[2][2]);
void Traverse(int row, int col);
int graph[2][2];
visits visited[2][2];
int len=0;
int num[4];
int main()
{
int col;
int row;
int i;
int j;
for(i=0;i<2;i++)
for(j=0;j<2;j++)
{cin>>graph[i][j];}
CleartheGrid(visited);
Traverse(1,1); // fix this with your loop
cin>>i;
return 0;
}
void Traverse( int row, int col)
{
if(row < 0 || row >1 || col < 0 || col > 1)
return;
if(visited[row][col]==v)
return;
num[len]=graph[row][col];
len++;
visited[row][col]=v;
Traverse(row-1,col-1);
Traverse(row-1,col);
Traverse(row-1,col+1);
Traverse(row,col+1);
Traverse(row,col-1);
Traverse(row+1,col+1);
Traverse(row+1,col);
Traverse(row+1,col-1);
// displaying
if(len == 4)
{
for(int n=0;n<4;n++) cout<<num[n]<<" ";
cout<<endl;
}
len--;
visited[row][col]=nv;
}
void CleartheGrid(visits visited[2][2])
{
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
visited[i][j]=nv;
}
Addapt it.