Hello Everyone,
I am required to write a program which, when given an nxn 2D array of char, and the specified coordinates of a specific point in that array, returns thelargest number of horizontal, vertical or diagonal contiguous (side-by-side) sequence of points
of that same char value that intersects with the given point.
The way I took on this problem was to:
1) First find out the number of points with the same char value up, down, right, left, north-east, north-west, south-east, and south-west of the given point.
2)Add up+down+1(the one is for the point itself), north-west+south-east+1, etc...
3) Finally I compared the four values (updown, rightleft, NESW, NWSE) and returned the largest one.
Well, that's how the program is supposed to work in theory but as you can probably guess it doesn't work. In addition to telling me what I'm doing wrong, is there a simpler way to do what I am trying to accomplish?
Thanks in advance
Here's the code:
Code:
int findLongest(char **board, int n, int row, int col)
{
char current;
int rightleft, updown, NESW, NWSE;
int r, c, c1=0, c2=0, c3=0, c4=0, c5=0, c6=0, c7=0, c8=0, d;
int t1=1, t2=1, t3=1, t4=1, t5=1, t6=1, t7=1, t8=1;
current=board[row][col];
//check Above: col remains the same
for(r=row-1;r>=0||t1!=0;r--)//with the condition r>=0 I made sure not to accidentally check values outside of the array
{
if(current==board[r][col])//checks if above point is same
{
c1++;
}
else
{
t1=0;//if we reach a point which is not the same (so we can exit)
}
}
//check Below: col remains the same
for(r=row+1;r<n||t2!=0;r++)
{
if(current==board[r][col])
{
c2++;
}
else
{
t2=0;
}
}
//check Right: row remains the same
for(c=col+1;c<n||t3!=0;c++)
{
if(current==board[row][c])
{
c3++;
}
else
{
t3=0;
}
}
//check Left: row remains the same
for(c=col-1;c>=0||t4!=0;c--)
{
if(current==board[row][c])
{
c4++;
}
else
{
t4++;
}
}
//check NE: row-d, col+d (we stop when either col==n-1||row==0)
for(d=1;d<=n||t5!=0;d++)
{
if(col+d==n-1||row-d==0)
{
t5++;
}
if(board[row-d][col+d]==current&&t5==0)
{
c5++;
}
else
{
t5++;
}
}
//check SW: row+d, col-d (we stop when either col==0||row==n-1)
for(d=1;d<=n||t6!=0;d++)
{
if(col-d==0||row+d==n-1)
{
t6++;
}
if(board[row+d][col-d]==current&&t6==0)
{
c6++;
}
else
{
t6++;
}
}
//check SE: row+d, col+d (we stop when either col==n-1||row==0)
for(d=1;d<=n||t7!=0;d++)
{
if(col+d==n-1||row+d==0)
{
t7++;
}
if(board[row+d][col+d]==current&&t7==0)
{
c7++;
}
else
{
t7++;
}
}
//check NW: row-d, col-d (we stop when either col==0||row==0)
for(d=1;d<=n||t8!=0;d++)
{
if(col-d==0||row-d==0)
{
t8++;
}
if(board[row-d][col-d]==current&&t7==0)
{
c8++;
}
else
{
t8++;
}
}
rightleft=c3+c4+1;
updown=c1+c2+1;
NESW=c8+c6+1;
NWSE=c5+c7+1;
if(rightleft>=updown&&rightleft>=NESW&&rightleft>=NWSE)
{
return rightleft;
}
else if(updown>=rightleft&&updown>=NESW&&updown>=NWSE)
{
return updown;
}
else if(NESW>=updown&&NESW>=rightleft&&NESW>=NWSE)
{
return NESW;
}
else
{
return NWSE;
}
}