矩阵归零(Zero Puzzling)_Java

http://oj.acmclub.cn/problems/1026   

题目描述

There is a matrix with m rows and n columns. An element of the matrix has at most four adjacent elements(up,down,left,right). You can add a same number to a pair of adjacent elements of the matrix. By doing this operation repeatedly, can you make the matrix zero?

输入描述

A line contains m and n indicating the rows and columns of the matrix(0<m,n<5)
Each of the following m lines contains n integers(-10^6<=each integer<=10^6)
Input is terminated by one line contains two zeros.

输出描述

If the matrix can be converted into zero,output "Yes" on a line otherwise output "No" on a line.

样例输入

2 2
1 1
1 0

2 2
0 0
1 1

0 0

样例输出

No
Yes

提示

染色问题


.......全英文....... 步骤1.打开有道 2.翻译全篇 3. 回归正题

今日英语单词积累:

matrix:矩阵    element:元素    adjacent:临近的   terminated:终止

You can add a same number to a pair of adjacent elements of the matrix. 

您可以向矩阵的一对相邻元素添加相同的数字。


##问题大意及思路

学习至:矩阵归零 - jiu~ - 博客园

题意:给定一个m行n列的数字矩阵,问能否通过反复使用给定的操作,使得最终矩阵里的所有数字都为0.题目允许的操作是对矩阵中某对相邻数都加上同一个数值。

思路:每个相邻对定是由一黑一白组成。令矩阵中所有白加起来为s1,所有黑加起来为s2。每次操作都会在s1和s2同时加上一个相同的数,因此不会改变s1和s2的差值。故而,要想获得零矩阵,s1与s2的差值一定为0。这是必要条件,那是否充分呢?是的。如果s1=s2,那么我们可以把矩阵所有的数通过操作集中要一个格子p上,假设p为白,那么s2=0,又s1=s2,故而p=0,获得零矩阵。


Java实现代码:

import java.util.Scanner;

//矩阵归零
public class Main {
public static void main(String [] args){
	Scanner scanner=new Scanner(System.in);
	//循环输入以00结尾
	while(scanner.hasNextInt()){
		int m=scanner.nextInt();
		int n=scanner.nextInt();
		if(m==0||n==0) break;
		//记录黑白色块上的数值
		int s1=0,s2=0;
		for(int i=1;i<=m;i++){
		   for(int j=1;j<=n;j++){
			   int t=scanner.nextInt();
			   //例如 矩阵1,1 和2,2 不相邻,他们都是白色块,即i+j为偶数
			   //矩阵元素1,2 和2,1也不相邻,他们都是黑色块,即i+j为奇数
			   if((i+j)%2==0) s1=s1+t;
			   else s2=s2+t;							
		   }
		  } 
		//充要条件,s1与s2 相等 ,方可通过相邻方块加减同一个数,使得矩阵变成0矩阵
	    if(s1==s2)    System.out.println("Yes");
	    else   System.out.println("No");
	  
	}
}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小才在学习Lu_lu

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

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

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

打赏作者

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

抵扣说明:

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

余额充值