Flip The Card OpenJ_POJ - 1000

这篇文章讨论了如何通过最少的操作次数,将一个N×N矩阵中的卡片从向下放置变为全部向上。给定初始状态和每次翻转的M×M子矩阵大小,挑战在于找出实现目标所需的最短操作序列。输入包括矩阵中卡片的初始方向,输出为达到所有卡片朝上的最小操作数,无解时输出-1。
摘要由CSDN通过智能技术生成

There are N× Ncards, which form an N× Nmatrix. The cards can be placed upwards or downwards. Now Acer is going to do some operations so that all the cards are placed upwards after the operations. In each operation, Acer can flip over exactly an M× Msub-matrix of cards. Acer wants to know the minimum number of operations to achieve his goal. 

Input

The first line contains two integers, N and M (0 < M ≤ N ≤ 1000).

Each of the next N lines contains N integers. If the integer is 1, the corresponding card is placed upwards initially; otherwise it is placed downwards initially. 

Output

Output an integer, which indicate the minimum number of operations. If there is no solution, output -1. 

Sample Input

4 2
1 1 0 0
0 0 1 1
1 1 1 1
0 0 0 0

Sample Output

5
#include<iostream>
int a[1001][1001];
int n,m;
int cnt=0;
void dfs(int x){
    if (x+m>n){
        for(int i=x;i<n;i++){
            for(int j=0;j<n;j++){
                if(a[i][j]==0){
                    cnt=-1;
                    return;
                }
            }
        }
        return;
    }
    for(int i=0;i<n;i++){
        if(a[x][i]!=1){
            if(i+m>n){
                cnt=-1;
                return;
            }
            cnt++;
            for(int k=x;k<x+m;k++){
                for(int j=i;j<i+m;j++){
                    a[k][j]=!a[k][j];
                }
            }
        }
            }
    dfs(x+1);
}
using namespace std;
int main()
{
    cin>>n>>m;
    for(int i=0;i<n;i++){
        for(int j=0;j<n;j++){
            cin>>a[i][j];
        }
    }
    dfs(0);
    cout<<cnt;
    return 0;
    
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

郭晋龙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值