TZOJ 4267 An Easy Puz(深搜)
描述
Wddpdh find an interesting mini-game in the BBS of WHU, called “An easy PUZ”. It’s a 6 * 6 chess board and each cell has a number in the range of 0 and 3(it can be 0, 1, 2 or 3). Each time you can choose a number A(i, j) in i-th row and j-th column, then the number A(i, j) and the numbers around it (A(i-1, j), A(i+1, j),A(i, j-1),A(i, j+1), sometimes there may just be 2 or 3 numbers.) will minus 1 (3 to 2, 2 to 1, 1 to 0, 0 to 3). You can do it finite times. The goal is to make all numbers become 0. Wddpdh now come up with an extended problem about it. He will give you a number N (3 <= N <= 6) indicate the size of the board. You should tell him the minimum steps to reach the goal.
输入
The input consists of multiple test cases. For each test case, it contains a positive integer N(3 <= n <= 6). N lines follow, each line contains N columns indicating the each number in the chess board.
输出
For each test case, output minimum steps to reach the goal. If you can’t reach the goal, output -1 instead.
样例输入
3
1 1 0
1 0 1
0 1 1
3
2 3 1
2 2 1
0 1 0
样例输出
2
3
题意
给你个N*N的矩阵,每次操作选择(i,j),然后(i,j)和周围4格都-1,3->2->1->0->3。问最少操作次数。
题解
爆搜4^36肯定不行,考虑优化。
可以发现,如果确定第一行每个位置的变化次数,那么下一行的变化次数也就确定了,最后判断是否每个数都变成0。
总时间复杂度O(4^6*36)。
代码
#include<bits/stdc++.h>
using namespace std;
int n,a[][],c[][],b[],minn;
int dx[]={,,,,-};
int dy[]={,-,,,};
void dfs(int p,int ans)
{
if(p==n+)
{
for(int i=;i<=n;i++)for(int j=;j<=n;j++)c[i][j]=a[i][j];
for(int j=;j<=n;j++)
for(int k=;k<;k++)
{
int xx=+dx[k];
int yy=j+dy[k];
if(xx>=&&xx<=n&&yy>=&&yy<=n)c[xx][yy]=(c[xx][yy]-b[j]+)%;
}
for(int i=;i<=n;i++)
for(int j=;j<=n;j++)
if(c[i-][j])
{
ans+=c[i-][j];
for(int k=;k<;k++)
{
int xx=i+dx[k];
int yy=j+dy[k];
if(xx>=&&xx<=n&&yy>=&&yy<=n)c[xx][yy]=(c[xx][yy]-c[i-][j]+)%;
}
}
for(int i=;i<=n;i++)
for(int j=;j<=n;j++)
if(c[i][j])
goto e;
minn=min(minn,ans);
e:return;
}
for(int i=;i<;i++)
{
b[p]=i;
dfs(p+,ans+i);
}
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
for(int i=;i<=n;i++)for(int j=;j<=n;j++)scanf("%d",&a[i][j]);
minn=1e9;
dfs(,);
printf("%d\n",minn==1e9?-:minn);
}
return ;
}
最新文章
- mysql的基本命令行操作
- Spring Data JPA 查询方法支持的关键字
- AESUtils.java
- 解决";waitForCondition(LockCondition) timed out (identity=23, status=0). CPU may be pegged. trying again.";问题
- python 装饰器和 functools 模块
- android滑动基础篇 - 触屏显示信息
- MYSQL更改root password时遇到Access Denied的解决办法
- Eclipse常用快捷键和调试方法
- Android 日夜间切换Demo
- 简洁灵活的前端框架------BootStrap
- ios、移动端 input type=date无法点击的问题解决方法
- HDU 1041	 Computer Transformation(找规律加大数乘)
- oracle数据库实例启动与关闭
- 使用Visual Studio Team Services持续集成(二)——为构建定义属性
- JAVA核心技术I---JAVA回顾
- Spring boot+Thymeleaf+easyui集成:js创建组件页面报错
- luogu2839 [国家集训队]middle
- Hive中MetaServer与HiveServer2的应用
- 个人github链接及git学习心得总结
- Confluence 6 设置其他页面为你空间的主页