C++回溯法实例分析

2020-01-06 13:04:05王振洲

int count = 0;
for (int i = 0; i < index; i++)
{
buff[states[i]] = true;
}
for (int i = 0; i < inputSize; i++)
{
if (buff[input[i]] == false)
  candidates[count++] = input[i];
}
*ncandidates = count;
return;
}

bool isSolution(int index, int inputSize)
{
if (index == inputSize)
return true;
else
return false;
}

void processSolution(char *input, int inputSize)
{
if (input == NULL || inputSize <= 0)
return;

for (int i = 0; i < inputSize; i++)
cout << input[i];
cout << endl;
}

void backTack(char *input, int inputSize, int index, char *states, int stateSize)
{
if (input == NULL || inputSize <= 0 || index < 0 || states == NULL || stateSize <= 0)
return;
 
char candidates[100];
int ncandidates;
if (isSolution(index, inputSize) == true)
{
processSolution(states, inputSize);
return;
}
else
{
constructCandidate(input, inputSize, index, states, candidates, &ncandidates);
for (int i = 0; i < ncandidates; i++)
{
  states[index] = candidates[i];
  backTack(input, inputSize, index + 1, states, stateSize);
}
}
}

void main()
{
char *candidates = new char[size];
if (candidates == NULL)
return;
backTack(str, size, 0, candidates, size);
delete []candidates;
}
对比上述两种情形,可以发现唯一的区别在于全排列对当前解向量没有要求,而字典序对当前解向量是有要求的,需要知道当前解的状态!
八皇后回溯法求解:

#include <iostream>

using namespace std;

int position[8];

void constructCandidate(int *input, int inputSize, int index, int *states, int *candidates, int *ncandidates)
{
if (input == NULL || inputSize <= 0 || index < 0 || candidates == NULL || ncandidates == NULL)
return;
 
*ncandidates = 0;
bool flag;
for (int i = 0; i < inputSize; i++)
{
flag = true;
for (int j = 0; j < index; j++)
{
  if (abs(index - j) == abs(i - states[j]))
  flag = false;
  if (i == states[j])
  flag = false;
}

if (flag == true)
{
  candidates[*ncandidates] = i;
  *ncandidates = *ncandidates + 1;
}
}
/*
cout << "ncandidates = " << *ncandidates << endl;
system("pause");*/

return;
}

bool isSolution(int index, int inputSize)
{
if (index == inputSize)
return true;
else
return false;
}

void processSolution(int &count)
{
count++;
}

void backTack(int *input, int inputSize, int index, int *states, int stateSize, int &count)