【题目链接】
https://www.lydsy.com/JudgeOnline/problem.php?id=1054
【算法】
广度优先搜索
【代码】
#include<bits/stdc++.h> using namespace std; const int dx[4] = {0,0,-1,1}; const int dy[4] = {-1,1,0,0}; const int MAXS = 1 << 16; struct info { int mp[5][5]; int step; } ; int i,j,k,goal,tx,ty,l,r,state; int mp[5][5],g[5][5]; info q[MAXS]; info cur,tmp; bool visited[MAXS]; inline bool valid(int x,int y) { return x > 0 && x <= 4 && y > 0 && y <= 4; } inline int get(int a[5][5]) { int i,j,ret = 0; int b = 1; for (i = 1; i <= 4; i++) { for (j = 1; j <= 4; j++) { ret += a[i][j] * b; b <<= 1; } } return ret; } int main() { for (i = 1; i <= 4; i++) { for (j = 1; j <= 4; j++) { mp[i][j] = getchar() - '0'; } getchar(); } getchar(); for (i = 1; i <= 4; i++) { for (j = 1; j <= 4; j++) { g[i][j] = getchar() - '0'; } getchar(); } goal = get(g); visited[get(mp)] = true; if (visited[goal]) { printf("0 "); return 0; } l = r = 1; memcpy(q[1].mp,mp,sizeof(q[1].mp)); q[1].step = 0; while (l <= r) { cur = q[l]; l++; for (i = 1; i <= 4; i++) { for (j = 1; j <= 4; j++) { if (cur.mp[i][j] == 1) { for (k = 0; k < 4; k++) { tx = i + dx[k]; ty = j + dy[k]; if (valid(tx,ty) && cur.mp[tx][ty] == 0) { swap(cur.mp[i][j],cur.mp[tx][ty]); state = get(cur.mp); if (!visited[state]) { visited[state] = true; if (state == goal) { printf("%d ",cur.step+1); return 0; } r++; memcpy(q[r].mp,cur.mp,sizeof(q[r].mp)); q[r].step = cur.step + 1; } swap(cur.mp[i][j],cur.mp[tx][ty]); } } } } } } return 0; }