Four Color Theorem java solution

2.1k Views Asked by At

I'm trying to implement the four color theorem. The four‐color theorem states that any map in a plane can be colored using four‐colors in such a way that regions sharing a common boundary (other than a single point) do not share the same color. There is a map separated into regions and the regions are put into an adjacency matrix and by using four colors I'm trying to color the map so that no two contiguous regions share the same color. The adjacency matrix is used to encode which region borders on another region. The columns and rows of the matrix are the regions while the cells contain a 0 if the two regions are not adjacent and a 1 if they border.

EDIT It has to be recursive

The adjacency matrix I am using is:

  A B C D
A 0 1 1 1
B 1 0 1 0
C 1 1 0 1
D 1 0 1 0

I am stuck on where to go from here. Thanks for help in advance.

Heres my code:

public class FourColorTheorem
{
   public static int[][] nums = {{0,1,1,1},{1,0,1,0},{1,1,0,1},{1,0,1,0}};
   public static int[] states;
   public static int[][] border;
   public static int[] setNeighs;
   public static int[][] neighbors;
   public static void main(String[] args)
   {
      createStatesArray();
      printArray();
      if(tryColor(0))
         System.out.println("Works");
      else
         System.out.println("Did not color all");

   }

   public static int[][] checkNeighbors(int r)
   {
      border = new int[4][4];
      for(int i=0;i<4;i++)
      {
         if(nums[r][i] == 0)
            border[r][i] = -1;
         else
            border[r][i] = 1;
      }
      return border;
   }

   public static void setNeighbors(int r)
   {
      for(int x = r;x<4;x++)
      {
         setNeighs[x] = states[x+1];
      }
   }

   public static boolean tryColor(int row)
   {
      int p=0;
      boolean q = false;

      if(row>4)
         return true;

      if(states[row] == 0)
      {
         states[row] = 1;
         setNeighbors(row);
      }
      if(row>1)
         if(setNeighs[row] == setNeighs[row-1])
            return false;

      int[][] temp = checkNeighbors(row);

      return false;
   }

   public static void printArray()
   {
      for(int i=0;i<4;i++)
      {
         for(int j=0;j<4;j++)
         {
            System.out.print(nums[i][j]);
         }
         System.out.println();
      }
      addBorder();
   }

   public static void createStatesArray()
   {
      states=new int[4];
      setNeighs=new int[4];
      for(int i=0;i<4;i++)
      {
         states[i] = -1;
         System.out.print(states[i]);
      }
      System.out.println();
   }   


   public static void addBorder()
   {
      border = new int[4][4];
      for(int i=0;i<4;i++)
      {
         for(int j=0;j<4;j++)
         {
            if(nums[i][j] == 0)
               states[i] = 1;
         }
      }
   }


}
0

There are 0 best solutions below