回溯的那些个算法

最近看算法,那些个回溯算法,总结起来可以一句话:撞了南墙就回头,回到撞墙以前的状态,总能找到路到罗马。既然到了罗马,我就知道来时的路。有点像《源代码》的情节,男主一死就往回,起死回生,再来一次,最后顺利找出凶手。


经典的回溯比如八皇后,二叉树求和的路径,数组的全排列,问题就不描述了,代码粘贴下,留个念想。


八皇后

#include <stdio.h>
#include <stdlib.h>
#define N 8
 int column[N+1];
 int rup[2*N+1];
 int lup[2*N+1];
 int queen[N+1]={0};
 int num;
 void backtrack(int);
 int main()
 {
     int i;
     num=0;
     for(i=1;i<=N;i++)
     column[i]=1;
    
     for(i=1;i<=2*N;i++)
     rup[i]=lup[i]=1;
     backtrack(1);
 system("pause");
 return 0;   
 }
 void backtrack(int i)
 {
   int j,x,y;
   if(i>N)
   {
     printf("\n解答%d\n",++num);
     for(y=1;y<=N;y++)
     {
        for(x=1;x<=N;x++)
        if(queen[y]==x)
           printf("Q");
           else
           printf(".");
        printf("\n");
     }
   }else
   {
      for(j = 1; j <= N; j++) {
            if(column[j] == 1 && rup[i+j] == 1 && lup[i-j+N] == 1) {
                queen[i] = j;
                column[j] = rup[i+j] = lup[i-j+N] = 0; // 
                backtrack(i+1);
                column[j] = rup[i+j] = lup[i-j+N] = 1;
            }
        }
 
   }
    
 }

二叉树求和


#include<iostream>
#include<string>
#include <stack>

using namespace std;
static int sum(0);
static int count(0);

template<class T>
struct BiNode
{
	T data;
	struct BiNode<T> *rchild,*lchild;
};

template<class T>
class BiTree
{
public:
	BiTree(){
		cout<<"int root node"<<endl;
		Create(root);
		if (NULL != root)
		{
			cout<<"root="<<root->data<<endl;
		}
		else
		{
			cout << "The BinaryTree is empty." << endl;
		}

	}
	~BiTree(){Release(root);}
	int Depth(){return Depth(root);}
	int FindPath(T i)
	{
		stack<BiNode<T>*> sta;
		return FindPath(i, root, sta);
	};

private:
	BiNode<T> *root;
	void Create(BiNode<T>* &bt);
	void Release(BiNode<T> *bt);
	int Depth(BiNode<T>* bt);
	int FindPath(T i, BiNode<T>* bt, stack<BiNode<T>*> &sta);
};

template <class T>
void BiTree<T>::Release(BiNode<T> *bt) 
{
	
	if(bt==NULL)
	{
		Release(bt->lchild );
		Release(bt->rchild );
		delete bt;
	}
}

//先序遍历构建树 
template <class T>
void BiTree<T>::Create(BiNode<T>* &bt) 
{
	T ch;
    cin>>ch;
    if(ch== 0)bt=NULL;
    else
    {
	    bt=new BiNode<T>;
	    bt->data =ch;
	    cout<<"left child"<<endl;
	    Create(bt->lchild );
	    cout<<"right child"<<endl;
	    Create(bt->rchild );
    }
}


template <class T>
int BiTree<T>::Depth(BiNode<T>* bt)
{
	if (NULL == bt)
	{
		return 0;
	}
	int d1 = Depth(bt->lchild);
	int d2 = Depth(bt->rchild);
	return (d1 > d2 ? d1 : d2)+ 1;
}

//采用回溯法查找路径 
template <class T>
int BiTree<T>::FindPath(T i, BiNode<T>* bt, stack<BiNode<T>*> &sta)
{   static int count;
	if (NULL != bt)
	{
		sta.push(bt); //将根节点压栈 ,栈用来保存结果集 
	}
	sum += bt->data; 

	if (sum == i && bt->lchild == NULL && bt->rchild == NULL)//当求到和且左子树和右子数都为空也就是到了叶节点时,就找到了解 
	{ 
           //打印结果 
		stack<BiNode<T>*> sta2(sta);
		BiNode<T>* p;
		cout << "One of the path is: " ;
		while (!sta2.empty())
		{
			p = sta2.top();
			cout << p->data << " ";
			sta2.pop();
		}
		cout << endl;
		count ++;
	}
	//当没有到叶节点时,继续找。 
	if (NULL != bt->lchild)
	{
		FindPath(i, bt->lchild, sta);
	}
	if (NULL != bt->rchild)
	{
		FindPath(i,bt->rchild, sta);
	}
	//回溯时,需要回到之前的状态,所以要减去sum,并且弹栈。 
	sum -= bt->data;
	sta.pop();	
	return count;
}

int main()
{ 

    BiTree<int> a;
   cout << "There are " << a.FindPath(22) << " path all." << endl;
   system("pause");
   return 0;
}

打印数组的全排列


#include <iostream>
using namespace std;
void swap(int &a,int &b)//交换连个元素
{
    int tem;
    tem = a;
    a = b;
    b = tem;
}
int sum=0;
void cal(int *a,int first,int end)
{
    if(first == end)//如果递归到深层时,到最后交换的元素即时最后一个元素时就打印出来
    {
        sum++;
        for(int i = 0; i <= end; i++)
        cout<<a[i]<<" ";
        cout<<endl;
    }
    else
    {
        for(int i = first; i <= end; i++)
        {//循环遍历使得当前位置后边的每一个元素都和当前深度的第一个元素交换一次
            swap(a[first],a[i]);//使得与第一个元素交换
            cal(a,first+1,end);//深入递归,此时已确定前边的元素,处理后边子序列的全排列形式。
            swap(a[first],a[i]);//恢复交换之前的状态
        }
    }
}
int main()
{ 
    int a[4] = {1,2,3,4};
    cal(a,0,3);
    cout<<"一共"<<sum<<"种排列";
    system("pause");
    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值