【解题报告】 【NOIP2017】 棋盘

【NOIP2017】 棋盘

题目:棋盘

解题思路:

从左上向右下搜索,然后来一点剪枝就可以了,比较简单,毫无体验感

AC代码

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring> 
using namespace std;
const int inf=0x7fffffff;
int m,n;
int map[105][105];//如果是1,代表黄色;如果是2,代表红色;
int s[105][105];
int sx[4]={-1,0,1,0};
int sy[4]={0,-1,0,1};
int ans=inf;
void dfs(int x,int y,int cost,bool use)
{
	if(x<1||y<1||x>m||y>m)
	return ;
	if(cost>=s[x][y])
	return ;
	s[x][y]=cost;
	if(x==m&&y==m)
	{
		if(cost<ans)
		ans=cost;
		return ;
	}
	for(int i=0;i<4;i++)
	{
		int xx=x+sx[i];
		int yy=y+sy[i];
		if(map[xx][yy])
		{
			if(map[xx][yy]==map[x][y])
			dfs(xx,yy,cost,false);
			else
			dfs(xx,yy,cost+1,false);
		}
		else if(!use)
		{
			map[xx][yy]=map[x][y];
			dfs(xx,yy,cost+2,true);
			map[xx][yy]=0;//还原现场 
		}
	}
}
int main()
{
	memset(s,0x7f,sizeof(s));
	cin>>m>>n;
	for(int i=1;i<=n;i++)
	{
		int x,y,c;
		cin>>x>>y>>c;
		map[x][y]=c+1;
	}
	dfs(1,1,0,false);
	printf("%d", ans==inf ? -1 : ans);
	return 0;
}
posted @ 2019-09-07 23:27  wweiyi  阅读(228)  评论(0编辑  收藏  举报
js脚本