Example #1
0
        /// <summary>
        /// Solves the 2-SAT problem and returns a possible variable assignment if it exits.
        /// </summary>
        /// <returns>The variable assignment, or null if no solution exists.</returns>
        public bool[] Solve()
        {
            var sc = new StrongComponents(graph);

            scGraph = sc.CreateGraph();

            literalValue = new bool[n * 2];

            for (int i = 0; i < n; i++)
            {
                if (graph.vcomp[i * 2] == graph.vcomp[i * 2 + 1])
                {
                    return(null);
                }
            }

            literalMap = new List <int> [scGraph.Length];
            for (int i = 0; i < scGraph.Length; i++)
            {
                literalMap[i] = new List <int>();
            }

            for (int i = 0; i < n * 2; i++)
            {
                literalMap[graph.vcomp[i]].Add(i);
            }

            visited  = new bool[scGraph.Length];
            conflict = new bool[scGraph.Length];
            for (int i = 0; i < scGraph.Length; i++)
            {
                Dfs(i);
            }

            var var = new bool[n];

            for (int i = 0; i < n; i++)
            {
                if (!literalValue[i * 2] && !literalValue[i * 2 + 1])
                {
                    return(null);
                }
                var[i] = literalValue[i * 2];
            }
            return(var);
        }