#include <algorithm> #include <iostream> #include <queue> using namespace std; class Node{ public: int a[3][3]; int sum; Node(int s,int array[3][3]) { sum=s; for(int i=0;i<=2;i++) for(int j=0;j<=2;j++) a[i][j]=array[i][j]; } }; int function1(int array[3][3]) { int temp; temp=array[1][1]; array[1][1]=array[0][1]; array[0][1]=array[0][0]; array[0][0]=array[1][0]; array[1][0]=temp; return 0; } int function2(int array[3][3]) { int temp; temp=array[1][2]; array[1][2]=array[0][2]; array[0][2]=array[0][1]; array[0][1]=array[1][1]; array[1][1]=temp; return 0; } int function3(int array[3][3]) { int temp; temp=array[2][1]; array[2][1]=array[1][1]; array[1][1]=array[1][0]; array[1][0]=array[2][0]; array[2][0]=temp; return 0; } int function4(int array[3][3]) { int temp; temp=array[2][2]; array[2][2]=array[1][2]; array[1][2]=array[1][1]; array[1][1]=array[2][1]; array[2][1]=temp; return 0; } bool match(int array[3][3]) { int temp[3][3]={{1,2,3},{4,5,6},{7,8,9}}; for(int i=0;i<=2;i++) for(int j=0;j<=2;j++) if(array[i][j]!=temp[i][j]) return false; return true; } int main() { int matrix[3][3]; while(cin>>matrix[0][0]) { for(int row=0;row<=2;row++) for(int col=0;col<=2;col++) { if(row==0&&col==0) continue; cin>>matrix[row][col]; } queue<Node>store; Node current=Node(0,matrix); store.push(current); while(store.size()) { if(match(store.front().a)) { cout<<store.front().sum<<endl; break; } for(int t=1;t<=4;t++) { Node temp=store.front(); if(t==1) { function1(temp.a); store.push(Node(temp.sum+1,temp.a)); } if(t==2) { function2(temp.a); store.push(Node(temp.sum+1,temp.a)); } if(t==3) { function3(temp.a); store.push(Node(temp.sum+1,temp.a)); } if(t==4) { function4(temp.a); store.push(Node(temp.sum+1,temp.a)); } } store.pop(); } } return 0; } 花了一个早上写了一个代码,但提交的时候,发现爆内存了。上网搜了一下 发现要用什么康拖展开公式,先不管它,以后学了数据结构再看再改