15-puzzle

声明:此文由 Sakura 负责

上来先输入一个数,表示矩阵大小。大小必须处于 (1,5] 的范围。
2,4,6,8 分别表示 ,,,
输入完记得加 \n,一次只能输入一个数。
n=3 为例,结束状态是指:

  a b 
c d e 
f g h

现在已经发现了一种构造方式可以出解,复杂度约为 O(n3)
放个可以玩的。

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;
}

作者:Sakura-Lu

出处:https://www.cnblogs.com/Sakura-Lu/p/17169602.html

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。

posted @   hzoi_Sakura  阅读(54)  评论(1编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 【杂谈】分布式事务——高大上的无用知识?
more_horiz
keyboard_arrow_up dark_mode palette
选择主题
点击右上角即可分享
微信分享提示