[±¸Çö ¹æ¹ý]
- maze Å©±â ¸¸ÅÀÇ ÀÌÀü À§Ä¡¸¦ ±â¾ïÇÏ´Â ¹è¿ prev¸¦ ¸¸µé°í // element prev[MAZE_SIZE][MAZE_SIZE];
- À̵¿ °¡´É À§Ä¡¸¦ ÀúÀåÇÏ´Â enqueue_loc() ÇÔ¼ö¿¡¼ ÀÌÀü À§Ä¡¸¦ ±â¾ïÇÏ°Ô ÇÑ ´ÙÀ½ // prev[r][c] = here;
* Ãⱸ 'x' ÁöÁ¡¿¡ µµÂøÇϸé Ãⱸ À§Ä¡·ÎºÎÅÍ prev ¸¦ ã¾Æ°¡¸é¼ ¿ªÀ¸·Î Ãâ·Â (¼øȯ ÀÌ¿ë)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 | #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAZE_SIZE 6 #define QUEUE_SIZE 100 typedef struct { short r; short c; } element; typedef struct { element data[QUEUE_SIZE]; int front, rear; } QueueType; //Å¥: ³Êºñ ¿ì¼± Ž»ö(BFS), ½ºÅÃ: ±íÀÌ ¿ì¼± Ž»ö(DFS) void init_queue(QueueType* q) { q->front = q->rear = 0; } int is_empty(QueueType* q) { return (q->front == q->rear); } int is_full(QueueType* q) { return ((q->rear + 1) % QUEUE_SIZE == q->front); } void enqueue(QueueType* q, element item) { if (is_full(q)) { fprintf(stderr, "Å¥ Æ÷È ¿¡·¯\n"); return; } q->rear = (q->rear + 1) % QUEUE_SIZE; q->data[q->rear] = item; } element dequeue(QueueType* q) { if (is_empty(q)) { fprintf(stderr, "Å¥ °ø¹é ¿¡·¯\n"); exit(1); } q->front = (q->front + 1) % QUEUE_SIZE; return q->data[q->front]; } element here = { 1,0 }, entry = { 1,0 }; // ¹Ì·Î Ž»ö¿¡ »ç¿ëµÉ ¹è¿ element prev[MAZE_SIZE][MAZE_SIZE]; // °¢ À§Ä¡¿¡ ´ëÇØ ÀÌÀü À§Ä¡¸¦ ÀúÀå char maze[MAZE_SIZE][MAZE_SIZE] = { { '1', '1', '1', '1', '1', '1' }, { 'e', '0', '1', '0', '0', '1' }, { '1', '0', '0', '0', '1', '1' }, { '1', '0', '1', '0', '1', '1' }, { '1', '0', '1', '0', '0', 'x' }, { '1', '1', '1', '1', '1', '1' } }; // °æ·Î¸¦ Ãâ·ÂÇÏ´Â ÇÔ¼ö void print_path(element here) { if (here.r == entry.r && here.c == entry.c){ printf("°æ·Î: "); return; } print_path(prev[here.r][here.c]); printf("(%d, %d) -> ", here.r, here.c); } void enqueue_loc(QueueType* q, element here, int r, int c) { if (r < 0 || c < 0 || r >= MAZE_SIZE || c >= MAZE_SIZE) return; if (maze[r][c] != '1' && maze[r][c] != '.') { element tmp; tmp.r = r; tmp.c = c; enqueue(q, tmp); prev[r][c] = here; // ÀÌÀü À§Ä¡ ÀúÀå } } void maze_print(char maze[MAZE_SIZE][MAZE_SIZE]) { printf("\n"); for (int r = 0; r < MAZE_SIZE; r++) { for (int c = 0; c < MAZE_SIZE; c++) { printf("%c", maze[r][c]); } printf("\n"); } } int main(void) { int r, c; QueueType q; init_queue(&q); here = entry; while (maze[here.r][here.c] != 'x') { r = here.r; c = here.c; maze[r][c] = '.'; maze_print(maze); enqueue_loc(&q, here, r - 1, c); enqueue_loc(&q, here, r + 1, c); enqueue_loc(&q, here, r, c - 1); enqueue_loc(&q, here, r, c + 1); if (is_empty(&q)) { printf("½ÇÆÐ\n"); return -1; } else here = dequeue(&q); } print_path(here); printf("¼º°ø\n"); return 0; } | cs |