15-puzzle
声明:此文由 Sakura 负责
上来先输入一个数,表示矩阵大小。大小必须处于 \((1,5]\) 的范围。
按 2
,4
,6
,8
分别表示 ↓
,←
,→
,↑
。
输入完记得加 \n
,一次只能输入一个数。
以 \(n = 3\) 为例,结束状态是指:
a b
c d e
f g h
现在已经发现了一种构造方式可以出解,复杂度约为 \(O(n^3)\)。
放个可以玩的。
Game
#include <time.h>
#include <stdio.h>
#include <algorithm>
const int mx = 5;
int n, m, nx, ny, al;
int num[mx][mx];
int read();
void load();
void draw();
bool sol(int);
void move(int);
int main()
{
n = read(); m = n * n;
if (n > 5)
return 0;
load(); draw();
while (sol((read() >> 1) - 1));
return 0;
}
int read()
{
int x = 0;
char c = getchar();
while (c < '0') c = getchar();
do {
x = x * 10 + (c & 15);
c = getchar();
}while (c >= '0');
return x;
}
void load()
{
int x;
srand(time(0));
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= n; ++j)
num[i][j] = (i - 1) * n + j - 1;
nx = 1; ny = 1; al = m - 1;
long long tim = clock() + 3000000;
system("printf \"\\033c\"");
puts ("Loading...");
while (clock() <= tim || al == m - 1)
move(rand() & 3);
}
void draw()
{
system("printf \"\\033c\"");
for (int i = 1; i <= n; ++i)
{
for (int j = 1; j <= n; ++j)
if (!num[i][j])
printf (" ");
else
printf ("%c ", num[i][j] + 'a' - 1);
putchar('\n');
}
fflush(stdout);
}
bool sol(int a)
{
if (a >= 4 || a < 0)
{
draw();
return true;
}
move(a); draw();
return al != m - 1;
}
const int dx[4] = {1, 0, 0, -1}, dy[4] = {0, -1, 1, 0};
void move(int a)
{
int x = nx + dx[a], y = ny + dy[a];
if (x < 1 || x > n || y < 1 || y > n)
return;
al -= (num[x][y] == (x - 1) * n + y - 1);
al += (num[x][y] == (nx - 1) * n + ny - 1);
num[nx][ny] = num[x][y];
num[x][y] = 0;
nx = x; ny = y;
}