跳到正文

个人记录

7.9总结

原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 6 分钟

版本

  1. v1当前

3:P1379 八数码难题

思路:

2:P2730 [USACO3.2] 魔板 Magic Squares

思路:

经过观察发现,3*3的方格中上方对应着字符串中的上三个,下方对应着字符串中的下三个,右方对应着字符串中的下一个,左方对应着字符串中的上一个。于是写出方向数组d[4]={-3,3,1,-1};

但是在bfs还要注意,当d[i]==1,则原下标为2,5,8时无法走到下一个。当d[i]==-1,则原下标为3,6时无法走到上一个。

code

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
string a;
int d[4]={-3,3,1,-1},lc;
map<string,int> ma;//由于是用string存储,所以无法用int,我这里用的map。
struct ll
{
	string x;
	int wz,step=0;
};
void bfs(string aa,int xxx)
{
	queue<ll> q;
	q.push({aa,xxx,0});
	ma[a]=1;
	while(!q.empty())
	{
		ll t=q.front();
		q.pop();
		for(int i=0;i<4;i++)//枚举四种方向
		{
			string xx=t.x;
			int y=t.wz+d[i];
            if(d[i]==1&&(t.wz==2||t.wz==5||t.wz==8))//特判第一种
            {
                continue;
            }
            if(d[i]==-1&&(t.wz==6||t.wz==3))特判第二种
            {
                continue;
            }
			if(y>=0&&y<9)//如果未超出界限
			{
				swap(xx[t.wz],xx[y]);//将两数交换
				if(ma[xx]==0)//如果这种方案没试过
				{
					ma[xx]=1;
					if(xx=="123804765")//并且是目标方案
					{
						cout<<t.step+1;//输出步数
                        return ;
					}
					q.push({xx,y,t.step+1});
				}
			}
		}
	}
    cout<<-1;//没有可行方案输出-1。
}
signed main()
{
	ios::sync_with_stdio(0);
	cin.tie(0);cout.tie(0);
	cin>>a;//输入
    if(a=="123804765")//特判开始就是目标的情况
	{
		cout<<0;
		return 0;
	}
	for(int i=0;i<9;i++)//找出0的初始位置
	{
		if(a[i]=='0')
		{
			lc=i;
			break;
		}
	}
	bfs(a,lc);
	return 0;
}

P2730 [USACO3.2] 魔板 Magic Squares

思路

找出3种方法在原剧中做的改变

code

C++
#include<bits/stdc++.h>
using namespace std;
string tj,b="12345678",cc;
map<string,int> ma;
struct node
{
	string x,ss;
	int step;
};
void bfs()
{
	queue<node> q;
	q.push({"", "12345678", 0});
    ma["12345678"]=1;
	while(!q.empty())
	{
		node t;
		t=q.front();
		q.pop();
        if(cc==t.ss)
        {
            cout<<t.step<<"\n";
            cout<<t.x;
            return ;
        }
		for(int i=0;i<3;i++)
		{
    		string c=t.ss;
			if(i==0)
			{
				swap(c[0],c[7]);
				swap(c[1],c[6]);
				swap(c[2],c[5]);
				swap(c[3],c[4]);
			}
			else if(i==1)
			{
				swap(c[3],c[0]);
				swap(c[3],c[2]);
				swap(c[2],c[1]);
				swap(c[7],c[4]);
				swap(c[4],c[5]);
				swap(c[5],c[6]);
			}
			else if(i==2)
			{
				swap(c[1],c[2]);
				swap(c[1],c[6]);
				swap(c[6],c[5]);
			}
            // cout<<c<<"\n";
            if(ma[c]==0)
            {
                string jss=t.x;
                if(i==0)
                {
                    jss+='A';
                }
                else if(i==1)
                {
                    jss+='B';
                }
                else
                {
                    jss+='C';
                }
                ma[c]=1;
                q.push({jss,c,t.step+1});
            }
		}
	}
}
signed main()
{
    for(int i=1;i<=8;i++)
    {
        char lc; cin>>lc;
        cc=cc+lc;
    }
	bfs();
	return 0;
}
原文