I am tring to get this program together and can't seem to make it work. Ok. . this program is to take in a file with a matrix of zeros and numbers 1-9. The zeros are shaded and the numbers are part of a block. All numbers and the ones directly beside them make a block. the program is to count the squares in each block and tell me how many block and squares there are.
0 0 0 0 0 0 0 0
0 0 4 0 0 0 1 0
0 0 2 2 0 0 2 0
0 0 3 0 0 3 3 0
0 0 0 0 4 4 0 0
0 5 0 0 5 0 0 0
0 6 0 0 6 6 0 0
0 0 0 0 0 0 0 0
The borders of the matrix must be shaded. The out put of this program with this file should be:
block 1 contains 4 squares
block 2 contains 9 squares
block 3 contains 2 squares

Ok so I keep getting the wrong out put from the program and don't know where I'm going wrong
can anyone help me?

#include <stdio.h>
#include <stdlib.h>
#define  MAXLINELEN 18


FILE  *getOpen();
void   push(int *, int *);
void   popShow();
void   pop(int * , int *);
//STACK *createStack (void); 
//void   push(int *);
//void   pushCol(int *);

struct  Stack
{
     int     row;
     int     col;
     struct  Stack *priorAddr;
};

struct Stack *tosp;
 

struct  StackRow
{
     int     row;
     //int     col;

     struct  StackRow *priorAddr;
};
struct StackRow *tospRow;
/*struct  Stack
{
     int     element;
     struct  Stack *priorAddr;
};*/
struct  StackCol
{
     int     col;
     struct  StackCol *priorAddr;
};
struct StackCol *tospCol; 

/*struct  POSITION
{
     int      row;
     int      col;
};*/ 

 //struct  POSITION *pPos;


int main()
{  
   FILE        *inFile;       
      
   int          nrows;             
   int          ncols;             
   int          i;
   int          row;
   int          col;
   char         singleLine[MAXLINELEN];
   int          size;
   int          location;
   int          rowElement;
   int          colElement;
   int          countSquares;
   int          block;
       
   
   
   // Open the matrix text file.
   inFile = getOpen();
   tosp = NULL;
   
   // Reads in the file line by line to determine the number of rows and columns.
   nrows = 0;
   ncols = 0;
   while (fgets(singleLine, MAXLINELEN - 1, inFile) != NULL)
   {
         nrows++;
         ncols++;
         printf("#%d: %s\n", nrows, singleLine);
   }
   size = nrows * ncols;
   printf("The size of the Matrix is: %d \n", size);
   
   // Dynamically allocates the matrix.
   char   matrix[nrows][ncols];
   
   if(matrix == NULL)
   {
        printf("Out of memory.\n");
        exit(1);
   }
  
  
   printf("Memory allocated successfully!\n");
   
   // Populate the matrix with the data from the file.
   rewind(inFile);
   for (row = 0; row < nrows; row++)
    {
        for (col = 0; col < ncols; col++)
        {
           if (fscanf(inFile, "%c ", &matrix[row][col]) == 1)
           {
                printf("%c ", matrix[row][col]);
           }
           
        }
        putchar('\n');
    }
   
    // Search for every non-zero character in the matrix.
    for (rowElement = 0; rowElement < row; rowElement++)
    {
        for (colElement = 0; colElement < col; colElement++)
        {
            if (matrix[rowElement][colElement] > '0')
            {
                 printf("Non-Zero Character is at Row: %d  Col: %d\n", rowElement, colElement);
                 push(&rowElement, &colElement);
            }
        }
    }
   
   popShow();
  
   
   printf("Number of squares: %d\n", countSquares);
   printf("Number of blocks: %d\n", block);
   
   
   
   
   
   
   
   
   system("pause");
   return 0;
   
}
   
/* =============================================
                   getOpen
   =============================================
   This function opens the file for reading, and 
   returns the file name back to the program for 
   use.
*/
FILE *getOpen()
{
     FILE *fname;
     char name[21];
     
     printf("\nEnter a file name: ");
     gets(name);
     fname = fopen(name, "r");
     if (fname == NULL)
     {
          printf("Can not open the file %s.\n", name);
          exit(1);
     }
     printf("File was successfully opened!\n");
     
     return(fname);
}

/* ==============================================
                       push                      
   ==============================================
   This function pushes the element onto the 
   stack.
*/

void push(int *row, int *col)
{
     struct Stack *newPtr;
     
     newPtr = (struct Stack *) malloc(sizeof (struct Stack ));
     if (newPtr == (struct Stack *) NULL)
     {
          printf("\nFailed to allocate memory \n");
          exit(1);
     }
          
     newPtr->row = *row; 
     newPtr->col = *col;
     newPtr->priorAddr = tosp;
     tosp = newPtr;
}

/* ===========================================
                    popShow
   ===========================================
   This function pops the elements off of the
   stack and displays them.
*/

void popShow()
{
     int  row;
     int  col;
     void pop(int *, int *);
     
     printf("\nPopped from the stack are:\n");
     
     while (tosp != NULL)
     {
        pop(&row, &col);
         printf("Row: %d   Col: %d\n", row, col);
     }
}

/* ===========================================
                         pop
   ===========================================
   This function pops the data off the stack.
*/

void pop(int *row, int *col)
{
     struct Stack *tempAddr;
     
     tosp->row = *row;
     tosp->col = *col;
     tempAddr = tosp->priorAddr;
     free(tosp);
     tosp = tempAddr; 
}

I do know that in lines 115 through 126 there should be somthing that when a non-zero is found it stores that location in a temp. and then looks next to it if not below it and to the other side so on and so forth... in order to find the non-zeros that are directly adjacent to each other. Something like
Location counter
up(location, locRow -1, locColumn)
right(location, locRow, locColumn +1)
left(location, locRow, locColumn -1)
down(location, locRow +1, locColumn)
I just don't know how to implement it in C code.
This is not ment to be a program that takes weeks to write, but in my case it is. I don't know what I'm doing and am looking up everything.

I'll take a look at it in about 2 hours. May use an array instead of a stack, but we'll see.

I am supposed to use stacks and recursive codes but I will take any help I can get. I'm about to lose my mind! Thanks for looking at it :)

the recursive stack is because they're trying to teach you a concept, not just so you can 'get it done'

you definitely should do it the way that's required even if another way seems easier.

i was going to look at this myself, but i'm at work and don't have time right now to sit down and debug it.

Edited 6 Years Ago by jephthah: n/a

As it turns out, this is a beautifully recursive algorithm example. Even if I didn't have to do this recursively, I would choose that way for this problem.

Generally, problem solving is easier without things like dynamic memory allocations structures, and recursion. But here, it's just too elegant to not use it.

I just got back, so let me get some stuff put away and run your code and see what's up.

It looks like somebody knew what they were doing in parts of the program -

and then they went criminally insane ;) ;)

I finally got it to compile, at least.

Well... I don't know C, so I had to do some self teaching. That didn't work out to well. Do you think you could give me some tips or tell me when I went insane.

No way should this be your first program!

When you want to dynamically create a 2D array, (using an array of pointers to each row, as is commonly done), the C syntax is:

#include <stdlib.h>   //for malloc

int **A;

//say your # of rows is 10, and the # of columns is 8
*A = malloc(10 * sizeof(int *)); 
//then:
for(int i = 0; i < 8; i++) 
  A[i] = malloc(8 * sizeof(int));  //note no * after int, here

//When you're done, free the memory, in reverse order:
for(i = 0; i < 8; i++)
  free(A[i]);
//then
free(A);

It was maddening, trying to separate the good from the bad, so a lot of the code just went under the delete button.

This is a nice problem, but you're not ready for it. Study up. I won't be posting up a completed program, because there are so many code leeches around.

I just had an encounter with one, (another C forum), regarding a poker program. I thought it was for a poker player, but no - it was just for an assignment. He had no clue about the programming needed, but he was good at asking for help, and taking all the code he could get, of course. Grrrrr!

Edited 6 Years Ago by Adak: n/a

No way should this be your first program!

When you want to dynamically create a 2D array, (using an array of pointers to each row, as is commonly done), the C syntax is:

#include <stdlib.h>   //for malloc

int **A;

//say your # of rows is 10, and the # of columns is 8
*A = malloc(10 * sizeof(int *)); 
//then:
for(int i = 0; i < 8; i++) 
  A[i] = malloc(8 * sizeof(int));  //note no * after int, here

//When you're done, free the memory, in reverse order:
for(i = 0; i < 8; i++)
  free(A[i]);
//then
free(A);

It was maddening, trying to separate the good from the bad, so a lot of the code just went under the delete button.

This is a nice problem, but you're not ready for it. Study up. I won't be posting up a completed program, because there are so many code leeches around.

I just had an encounter with one, (another C forum), regarding a poker program. I thought it was for a poker player, but no - it was just for an assignment. He had no clue about the programming needed, but he was good at asking for help, and taking all the code he could get, of course. Grrrrr!

Well... I had it done whit a 2D array and was told that I was not allowed to use arrays. So, I had to change it. As in the char matrix [row][col]. and then I got thrown way out of wack. The thing I would most like help with is, how I would go about looking through the matrix for the blocks. I understand logicaly how to do it (as I posted that befor) but have no idea how to implement it. I have tried to find some form of tutorial for that and the flag to tell me where I have been and have come up with nothing. If you have any ideas on the search or the flag, that would be great. Or even a tutorial that can help me.
Also, I know that this is ridiculous for my first C program, no one in the class is getting it, execpt one guy who works in programming.:confused:

I found out this is called either a "floodfill" algorithm, or rarely, "minesweeper cascade".

Wikipedia has a nice entry on "floodfill" algo. Google shows both recursive and non-recursive hits for it.

This article has been dead for over six months. Start a new discussion instead.