#include #include #include #include #include #include #include typedef struct Vertex { int row; int col; int count; } Vertex; typedef struct Queue { Vertex *array; int back; int front; int size; } Queue; Queue newQueue (int s) { Queue q; q.array = malloc ( s * sizeof ( Vertex ) ); q.back = 0; q.front = 0; q.size = s; return q; } int isEmptyQueue( Queue q ) { return ( q.back == q.front ); } void doubleQueueSize ( Queue *qp ) { int i; int oldSize = qp->size; qp->size = 2 * oldSize; qp->array = realloc(qp->array, qp->size * sizeof(Vertex) ); for ( i = 0; i < qp->back; i++ ) { qp->array[ oldSize + i ] = qp->array[i]; } qp->back = qp->back + oldSize; } void enqueue ( Vertex item, Queue *qp ) { qp->array[qp->back] = item; qp->back = ( qp->back + 1 ) % qp->size; if ( qp->back == qp->front ) { doubleQueueSize(qp); } } Vertex dequeue ( Queue *qp ) { Vertex item; if ( isEmptyQueue( *qp ) ) { printf("Empty Error\n"); } item = qp->array[qp->front]; qp->front = ( qp->front + 1 ) % qp->size; return item; } void freeQueue ( Queue q ) { free(q.array); } int **twoDArray(int size) { int **array = malloc(size * sizeof(int*)); for(int i = 0; i < size; i++ ) { array[i] = calloc(size, sizeof(int)); } return array; } void freeArray(int **array, int size) { for(int i = 0; i < size; i++ ) { free(array[i]); } free(array); } void enqValid(Vertex v, int a, int b, int size, int **visit, Queue *queue) { if(v.row + a >= 0 && v.row + a <= size - 1 && v.col + b >= 0 && v.col + b <= size - 1) { Vertex newV; newV.row = v.row + a; newV.col = v.col + b; newV.count = v.count + 1; if (visit[newV.row][newV.col] == 0) { visit[newV.row][newV.col] = 1; enqueue(newV, queue); } } } int BFS(Vertex start, int a, int b, int size, int **visit) { visit[start.row][start.col] = 1; Queue queue = newQueue(10); enqueue(start, &queue); while (!isEmptyQueue(queue)) { Vertex v = dequeue(&queue); if (v.row == size - 1 && v.col == size - 1) return v.count; enqValid(v, a, b, size, visit, &queue); enqValid(v, a, -b, size, visit, &queue); enqValid(v, -a, b, size, visit, &queue); enqValid(v, -a, -b, size, visit, &queue); enqValid(v, b, a, size, visit, &queue); enqValid(v, b, -a, size, visit, &queue); enqValid(v, -b, a, size, visit, &queue); enqValid(v, -b, -a, size, visit, &queue); } return -1; } int main(){ int n; scanf("%d",&n); // your code goes here int **answer = twoDArray(n-1); Vertex start; start.row = 0; start.col = 0; start.count = 0; for (int i = 0; i < n-1; i++ ) { for (int j = 0; j < n-1; j++ ) { int **visit = twoDArray(n); answer[i][j] = BFS(start, i+1, j+1, n, visit); freeArray(visit, n); } } for (int i = 0; i < n-1; i++ ) { for (int j = 0; j < n-1; j++ ) { if (j != n-2) printf("%d ", answer[i][j]); else printf("%d\n", answer[i][j]); } } freeArray(answer, n-1); return 0; }