Advertisement
Guest User

Untitled

a guest
Nov 19th, 2017
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.60 KB | None | 0 0
  1. #include <iostream>
  2. #include <stdio.h>
  3. #include <stack>
  4.  
  5. bool isSafe(int n, int* graph, int vertex_nb, int* colors, int c)
  6. {
  7. for(int i=0; i<n; i++)
  8. {
  9. if(graph[n*vertex_nb+i] && c == colors[i])
  10. {
  11. return false;
  12. }
  13. }
  14. return true;
  15. }
  16.  
  17. bool graphColoringUtil(int* graph, int vertex_nb, int colors_nb, int* colors, int n)
  18. {
  19. bool all_colored = true;
  20. for(int i = 0; i < vertex_nb; i++)
  21. {
  22. if(!colors[i])
  23. all_colored = false;
  24. }
  25. if(all_colored)
  26. return true;
  27. for(int c = 1; c <= colors_nb; c++)
  28. {
  29. if(isSafe(n, graph, vertex_nb, colors, c))
  30. {
  31. colors[n] = c;
  32. if(graphColoringUtil(graph, vertex_nb, colors_nb, colors, n+1))
  33. {
  34. return true;
  35. }
  36. colors[n] = 0;
  37. }
  38. }
  39. return false;
  40. }
  41.  
  42. int main()
  43. {
  44. int tests = 0;
  45. scanf("%d", &tests);
  46. for(int t = 0; t < tests; t++)
  47. {
  48. int vertex_nb = 0, colors_nb = 0;
  49. scanf("%d %d", &vertex_nb, &colors_nb);
  50. int graph[vertex_nb][vertex_nb] = {0};
  51. for(int i = 0; i < vertex_nb; i++)
  52. for(int j = 0; j < vertex_nb; j++)
  53. scanf("%d", &graph[i][j]);
  54. int colors[vertex_nb] = {0};
  55. if(graphColoringUtil(graph[0], vertex_nb, colors_nb, colors, 0))
  56. {
  57. for(int i = 0; i < vertex_nb; i++)
  58. printf("%d ", colors[i]);
  59. puts("");
  60. }
  61. else
  62. {
  63. puts("No solution!");
  64. }
  65.  
  66. }
  67. return 0;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement