钻石独立棋的用HASH表和栈改进版

  虽然只是小程序,呵呵,顺便多学点STL吧,就把它由原来的遍历搜索改成用HASHMAP存储改进,时间加快了不少哦,嗯,HASHKEY有二种,一种就用一个LONG LONG来表示,呀,刚好多了二位,不然INT就够了,另一种就用一串STRING来了,这里是用STRING的,这样的搜索模板就更完整了哦:)
/*
CODY BY 我的BLOG AT 2004.10.9
独立钻石棋问题, 深度优先搜索,尽量清除重复点
2004.10.18
利用HASHMAP改进CLOSED集,利用STACK改进OPEN集.

棋盘编号布局如下:
      01 02 03
      04 05 06
07 08 09 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
   28 29 30
   31 32 33
*/
#include <iostream>
#include <fstream>
#include <algorithm>
#include <stack>
#include <string>
#include <hash_map>

#include "Node.h"
using namespace std;
using namespace stdext;

stack<Node> open;
hash_map<string,Node> closed;
typedef pair <string, Node> Pair;
hash_map<string,Node>:: const_iterator rcIter;


// 判断next结点是否已扩展过,是返回true,否则false
bool extended(Node &next);
// 搜索解
void search();

int main(void)
{
 search();
 system("pause");
 return 0;
}

void search()
{
 // 初始化
 Node first;
 for(int i=1;i<=33;i++){
  first.c[i] = 1;
 }
 first.c[17] = 0;
 first.key = 0;
 open.push(first);

 // 开始循环
 while(!open.empty()){
  //cout<<"正在搜索......         已扩展结点:"<<closed.size()<<"/n";
  Node tmp = open.top();
  open.pop();

  // 看所取节点是否为目标节点
  if(tmp.moveid[0] >= 31 && tmp.c[17] == 1){
   tmp.output(cout);      // 输出解并返回
   ofstream out("out.txt");
   tmp.output(out);      
   return ;
  }

  // 若不是则生成所有的子状态
  Node next;
  bool hadit;
  for(int i = 1;i <= 33 ;i++){
   if(tmp.c[i] != 0){
    if( tmp.down(i,next)){
     if(extended(next) == false){ // 还没扩展过
      open.push(next);
     }
    }
    if( tmp.up(i,next)){
     if(extended(next) == false){ // 还没扩展过
      open.push(next);
     }
    }
    if( tmp.left(i,next)){
     if(extended(next) == false){ // 还没扩展过
      open.push(next);
     }
    }
    if( tmp.right(i,next)){
     if(extended(next) == false){ // 还没扩展过
      open.push(next);
     }
    }
   }
  }
  // 将刚才取出的open点放入closed表
  closed.insert ( Pair(tmp.getHashKey(),tmp));
 }
}

bool extended(Node &next)
{
 // 若next在closed中,即已扩展过了,返回true
 rcIter = closed.find(next.getHashKey());
 if(rcIter == closed.end()){
  return false;
 }else{
  return true;
 }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值