loading...

Write better code: Day 8 - Graph Coloring

twitter logo github logo Updated on ・1 min read

This post originally appeared on Arjun Rajkumar's blog. Arjun is a web developer based in Bangalore, India.

--

Day 8: Question 1

Given an undirected graph with maximum degree DD, find a graph coloring using at most D+1 colors.

-

If you want to follow along, feel free to post your answers in the comment.

My answers are in the comments.
This problem is from InterviewCake.

twitter logo DISCUSS (1)
markdown guide
 

Logic:

  • Each node in the graph has maximum D neighbours.
  • Given than there are maximum D+1 colours, we can assume that for each node there is atleast one color that is not used.
  • So, go thru each node and get the colors of all its neighbours.
  • Check to see which color is not included in this neighbouring color group, and assign the color to it.
def colour_graoh(colors, graph)
  graph.nodes.each do |node|

    all_neighbouring_colors = []

    node.neighbours.each do |neighbour|
      all_neighbouring_colors << neighbour.color if !all_neighbouring_colors.include?(neighbour.color)
    end

    colors.each do |color|
      node.color = color if !all_neighbouring_colors.include?(color)
      break
    end
end
Classic DEV Post from Sep 13 '19

Is it possible to get relevant industry experience on your own (not through working at a company)?

This is an anonymous post sent in by a member who does not want their name disclo...

Arjun Rajkumar profile image
Remote Ruby on Rails developer for hire.

Sore eyes?

dev.to now has dark mode.

Go to the "misc" section of your settings and select night theme ❤️