edited by
569 views
1 votes
1 votes

Let $A$ be a matrix of size row $\times$ col. $A$ has to be filled in a spiral clockwise fashion with successive integers from $1,2, \ldots$, row $\times$ col starting from the top left corner. For example, a $3 \times 4$ matrix should be filled in as follows: $$\begin{array}{cccc}1 & 2 & 3 & 4 \\ 10 & 11 & 12 & 5 \\ 9 & 8 & 7 & 6\end{array}$$ Fill in all the blanks in the following code snippet to do the above job. In the answer script, write only the while loop with the blanks filled-in.

#include<stdio.h>
#include<stdlib.h>
#define RIGHT 0
#define DOWN  1 
#define LEFT  2
#define UP    3

void spiralFill ( int **A, int r, int c) {
    int i, j, top, bottom, left, right, dir, k=1;
    i = j = 0; dir = RIGHT;
    top = 0; bottom = r-1; left = 0; right = c-1;
    while ((top <= _______ ) && (left <= _______ )) {
        A[i][j] = k; k++;
        switch (dir) {
        case RIGHT: if(j < _______) _______;
                    else{dir = _______; top = _______; i = _______;}
                    break;
        case DOWN: if(i < _______) _______;
                    else{dir = _______; right = _______; j = _______;}
                    break;            
        case LEFT: if(j > _______) _______;
                    else{dir = _______; bottom = _______; i = _______;}
                    break;
        case UP: if(i > _______) _______;
                    else{dir = _______; left = _______; j = _______;}
                    break;                    
        }
    }
}


int main() {
    int **A, row, col, i, j;
    printf("\n Row and column size::>");
    scanf("%d %d", &row, &col);
    
    A = (int **) calloc(row,sizeof(int *));
    for(i=0;i<row;i++){
        A[i] = (int *)calloc(col,sizeof(int));
    }
    spiralFill(A,row,col);
}
edited by

1 Answer

3 votes
3 votes
while ((top <= bottom) && (left <= right))

{ A[i][j] = k; k++; switch (dir)

{ case RIGHT: if(j < right) j++;

else{dir = DOWN; top = top+1; i = i+1;}

break; case DOWN: if(i < bottom) i++;

else{dir = LEFT; right = right-1; j = j-1;}

break; case LEFT: if(j > left) j--;

else{dir = UP; bottom = bottom-1; i = i-1;}

break; case UP: if(i > top) i--;

else{dir = RIGHT; left = left+1; j = j+1;}

break;

}

}

 

Nice question but easy one.

Related questions

0 votes
0 votes
2 answers
3
admin asked Aug 8, 2022
582 views
Let $G$ be a simple undirected graph having $n$ vertices with the property that the average of the degrees of the vertices in $G$ is at least $4.$ Consider the following ...
0 votes
0 votes
1 answer
4