次のプログラムをコーディングして、4 色マップ定理 (簡単に言えば、隣接する領域が同じ色になることなく、マップを 4 色だけで色付けできます) を再帰的に実装しました。すべてがコンパイルされますが、私の出力には誤ったデータが表示されます (今のところ値 0-3 ではなく、各領域の色に対して -1)。私の最大の疑問は、出力が正しくない理由です。
疑問に思っている方のために説明すると、入力ファイルは次のような隣接行列です。
0 1 0 1
1 0 1 0
0 1 0 1
1 0 1 0
これが私のコードです:
public class FourColorMapThm
{
public static boolean acceptable(int[] map, int[][] matrix, int r, int c)
{
for(int i = 0; i < map.length; i++)
{
if(matrix[r][i] == 1)
{
if(map[i] == c) return false;
}
}
return true;
}
public static boolean colorTheMap(int[] map, int[][] matrix, int r, int c)
{
boolean q = false;
int i = 0;
if(!acceptable(map, matrix, r, i)) return false;
map[r] = i;
boolean done = true;
for(int j = 0; j < map.length; j++)
{
if(map[j] == -1)
{
done = false;
}
}
if(done) return true;
do
{
i++;
q = colorTheMap(map, matrix, r+1, i);
if(q) return true;
}
while(i <= 3);
map[r] = -1;
return false;
}
public static void main(String[] args) throws IOException
{
Scanner in = new Scanner(System.in);
String snumRegions, fileName;
int numRegions;
System.out.print("Enter the number of regions: ");
snumRegions = in.nextLine();
numRegions = Integer.parseInt(snumRegions);
System.out.print("\nEnter filename for adjacency matrix: ");
fileName = in.nextLine();
in.close();
Scanner inFile = new Scanner(new FileReader(fileName));
PrintWriter outFile = new PrintWriter("coloredMap.txt");
int[][] matrix = new int[numRegions][numRegions];
int[] map = new int[numRegions];
//initializing matrix from file
for(int row = 0; row < matrix.length; row++)
{
for(int col = 0; col < matrix.length; col++)
{
matrix[row][col] = inFile.nextInt();
}
}
inFile.close();
//initialize map vals to -1
for(int i = 0; i < map.length; i++)
{
map[i] = -1;
}
colorTheMap(map, matrix, 0, 0);
outFile.println("Region\t\tColor");
for(int i = 0; i < map.length; i++)
{
outFile.println(i+1 + "\t\t" + map[i]);
}
outFile.close();
}
}