人工智能的书也在讲A*,正好顺便学学
// darkscope.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include#include using namespace std;struct node{ int state[3][3]; int x,y,g; node() {memset(state,0,sizeof(state)); x=0;y=0;g=0; } void show() { cout<<"--------"< <3;i++) { for (int j=0;j<3;j++) cout< <<" "; cout< <<"--------"< <3;i++) for (int j=0;j<3;j++) { cin>>ans.state[i][j]; if (ans.state[i][j]==0) { ans.x=i; ans.y=j; } } return ans;}node src,tar;int h_val(node a){ int ans=0; for (int i=0;i<3;i++) for (int j=0;j<3;j++) ans+=(a.state[i][j]!=tar.state[i][j]); return ans;}bool same(node &a,node &b){ for (int i=0;i<3;i++) for (int j=0;j<3;j++) if (a.state[i][j]!=b.state[i][j]) return false; return true; }void swap(int &a,int &b){ int t; t=a; a=b; b=t; }void ida_star(){ int pathlimit=h_val(src)-1; bool success=false; do { pathlimit+=1; src.g=0; stack Stack; Stack.push(src); do { node current=Stack.top(); Stack.pop(); if (same(current,tar)) success=true; else if (pathlimit>=current.g + h_val(current)) { if (current.x>0) { node b=current; b.g=current.g+1; swap(b.state[b.x][b.y],b.state[b.x-1][b.y]); b.x-=1; Stack.push(b); } if (current.x<2) { node b=current; b.g=current.g+1; swap(b.state[b.x][b.y],b.state[b.x+1][b.y]); b.x+=1; Stack.push(b); } if (current.y>0) { node b=current; b.g=current.g+1; swap(b.state[b.x][b.y],b.state[b.x][b.y-1]); b.y-=1; Stack.push(b); } if (current.y<2) { node b=current; b.g=current.g+1; swap(b.state[b.x][b.y],b.state[b.x][b.y+1]); b.y+=1; Stack.push(b); } } if (success) cout< <