2021-03-20个人赛补题H - Corrupted Images

H - Corrupted Images

题目链接: link.
题目描述:
Husam has a lot of free time, so he is using this time in repairing corrupted binary images.

A Binary image can be represented as 2-dimensional array consisting of n rows, each of which is divided into m columns. The rows are numbered from 1 to n from top to bottom, and the columns are numbered from 1 to m from left to right. Each cell is identified by a pair (x, y), which means that the cell is located at row x and column y. The possible values in the binary images are either zero or one.

A binary image is good if all cells in the first row, last row, first column, and last column are ones. Otherwise, the binary image is corrupted. If the binary image is corrupted, Husam will fix it.

Husam wants to fix the image with the minimum number of moves, such that in each move he can swap the values at two different cells.

Can you help Husam by calculating the minimum number of required moves to fix the image?
The first line contains an integer T, where T is the number of test cases.

The first line of each test case contains two integers n and m (3 ≤ n, m ≤ 50), where n is the number of rows in the binary image, and m is the number of columns in each row.

Then n lines follow, each line contains m characters, giving the binary image. All values in the binary image are either zero or one.
For each test case, print a single line containing -1 if Husam cannot fix the binary image. Otherwise, print the minimum number of required moves to fix the image.
样例

输入
3
3 3
111
101
111
4 4
1111
0111
1000
1111
4 5
10101
01010
10101
01010
输出
0
2
-1

题目大意:第一行,第一列,最后一行,最后一列都要用其余行列的元素修改为1,判断需要修改几次,若不能满足条件则输出-1.

这个题我在比赛做的时候想复杂了,拿过题一看,我首先想到的是bfs ,但仔细一想,其实挺简单,把外围,内部分别遍历一下,只要内部的1比外围的0多,即能满足条件。

代码如下(示例):

#include <bits/stdc++.h>
using namespace std;
char a[55][55];
int main() {
    int t;
    cin >> t;
    while (t--) {
        int n, m;
        cin >> n >> m;
       for(int i=0;i<n;i++)
         scanf("%s",&a[i]);
        int z = 0, y = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (i > 0 && i < n - 1 && j > 0 && j < m - 1) {
                    if (a[i][j] == '1') y++;
                } 
                else {
                    if (a[i][j] == '0') z++;
                }
            }
        }
        if (y >= z)
            cout << z << endl;
        else
            cout << -1 << endl;
    }
    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值