Advertisement
Guest User

Untitled

a guest
Nov 19th, 2019
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.31 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct Node {
  5.     int number;
  6.     struct Node *next;
  7. } Node;
  8.  
  9. Node *makeNode(int number) {
  10.     Node *result;
  11.     result = (Node*)malloc(sizeof(Node));
  12.     result->number = number;
  13.     result->next = NULL;
  14.    
  15.     return result;
  16. }
  17. void *insertNode(Node *Queue, int number) {
  18.     Node *cur = Queue;
  19.    
  20.     while (cur->next)
  21.         cur = cur->next;
  22.    
  23.     cur->next = makeNode(number);
  24. }
  25.  
  26. void printNode(Node *Queue) {
  27.     Node *cur = Queue;
  28.    
  29.     while (cur->next) {
  30.         cur = cur->next;
  31.         printf("%d ", cur->number);
  32.     }
  33.     printf("\n");
  34. }
  35.  
  36. void BFS(int arr[101][101], int max, int start) {
  37.     Node *Queue = makeNode(start);
  38.     int i, q_idx = 0;
  39.    
  40.     arr[start][start] = -1;
  41.    
  42.     while (Queue) {
  43.         printf("%d\n", Queue->number);
  44.        
  45.         start = Queue->number;
  46.         for (i = 1; i <= max; i++) {
  47.             if (arr[start][i] == 1) {
  48.                 arr[start][i] = arr[i][start] = 0;
  49.                
  50.                 if (arr[i][i] != -1) {
  51.                     arr[i][i] = -1;
  52.                     insertNode(Queue, i);
  53.                 }
  54.             }
  55.         }
  56.        
  57.         Queue = Queue->next;
  58.     }
  59. }
  60.  
  61. int main(void) {
  62.     int n, m, s, i, j, x ,y;
  63.     int arr[101][101];
  64.    
  65.     for (i = 0; i < 101; i++)
  66.         for (j = 0; j < 101; j++)
  67.             arr[i][j] = 0;
  68.    
  69.     scanf("%d %d %d", &n, &m, &s);
  70.    
  71.     for (i = 1; i <= m; i++) {
  72.         scanf("%d %d", &x, &y);
  73.         arr[x][y] = arr[y][x] = 1;
  74.     }
  75.    
  76.     BFS(arr, n, s);
  77.    
  78.     return 0;
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement