An N x N board contains only 0s and 1s. In each move, you can swap any 2 rows with each other, or any 2 columns with each other.

What is the minimum number of moves to transform the board into a "chessboard" - a board where no 0s and no 1s are 4-directionally adjacent? If the task is impossible, return -1.

Examples:
Input: board = [[0,1,1,0],[0,1,1,0],[1,0,0,1],[1,0,0,1]]
Output: 2
Explanation:
One potential sequence of moves is shown below, from left to right: 0110 1010 1010
0110 --> 1010 --> 0101
1001 0101 1010
1001 0101 0101 The first move swaps the first and second column.
The second move swaps the second and third row. Input: board = [[0, 1], [1, 0]]
Output: 0
Explanation:
Also note that the board with 0 in the top left corner,
01
10 is also a valid chessboard. Input: board = [[1, 0], [1, 0]]
Output: -1
Explanation:
No matter what sequence of moves you make, you cannot end with a valid chessboard.

Note:

  • board will have the same number of rows and columns, a number in the range [2, 30].
  • board[i][j] will be only 0s or 1s.

Approach #1: Array. [Math]

class Solution {
public int movesToChessboard(int[][] b) {
int N = b.length, rowSum = 0, colSum = 0, rowSwap = 0, colSwap = 0;
for (int i = 0; i < N; ++i) for (int j = 0; j < N; ++j)
if ((b[0][0] ^ b[i][0] ^ b[0][j] ^ b[i][j]) == 1) return -1;
for (int i = 0; i < N; ++i) {
rowSum += b[0][i];
colSum += b[i][0];
if (b[i][0] == i % 2) rowSwap++;
if (b[0][i] == i % 2) colSwap++;
}
if (rowSum != N/2 && rowSum != (N+1)/2) return -1;
if (colSum != N/2 && colSum != (N+1)/2) return -1;
if (N % 2 == 1) {
if (colSwap % 2 == 1) colSwap = N - colSwap;
if (rowSwap % 2 == 1) rowSwap = N - rowSwap;
} else {
colSwap = Math.min(N-colSwap, colSwap);
rowSwap = Math.min(N-rowSwap, rowSwap);
}
return (colSwap + rowSwap) / 2;
}
}

  

Analysis:

In a valid chess board, there are 2 and only 2 kinds of rows and one is inverse to the other. For example if there is a row 0101001 in the board, any other row must be either 0101001 or 1010110.

The same for colums.

A corollary is that, any rectangle inside the board with corners top left, top right, bottom left, bottom right must be 4 zeros or 2 zeros 2 ones or 4 ones.

Another important property is that every row and column has half ones. Assume the board is N * N:

If N = 2  * K, every row and every colum has K ones and K zeros.

If N = 2 * K + 1, every row and every col has K ones and K + 1 zeros or K + 1 ones and K zeros.

Since the swap process does not break this property, for a fiven board to be valid, this property must hold.

These two conditions are necessary and sufficient condition for a calid chessboard.

Once we know it is a valid cheese board, we start to count swaps.

Basic on the property above, when we arange the first row, we are actually moving all columns.

I try to arrange one row into 01010 and 10101 and I count the number of swap.

In case of N even, I take the minimum swaps, because both are possible.

In case of N odd, I take the even swaps.

Because when we make a swap, we move 2 columns or 2 rows at the same time.

So col swaps and row swaps shoule be same here.

Reference:

https://leetcode.com/problems/transform-to-chessboard/discuss/114847/C%2B%2BJavaPython-Solution-with-Explanation

782. Transform to Chessboard的更多相关文章

  1. [Swift]LeetCode782. 变为棋盘 | Transform to Chessboard

    An N x N board contains only 0s and 1s. In each move, you can swap any 2 rows with each other, or an ...

  2. [LeetCode] Transform to Chessboard 转为棋盘

    An N x N board contains only 0s and 1s. In each move, you can swap any 2 rows with each other, or an ...

  3. LeetCode All in One题解汇总(持续更新中...)

    突然很想刷刷题,LeetCode是一个不错的选择,忽略了输入输出,更好的突出了算法,省去了不少时间. dalao们发现了任何错误,或是代码无法通过,或是有更好的解法,或是有任何疑问和建议的话,可以在对 ...

  4. leetcode 学习心得 (4)

    645. Set Mismatch The set S originally contains numbers from 1 to n. But unfortunately, due to the d ...

  5. All LeetCode Questions List 题目汇总

    All LeetCode Questions List(Part of Answers, still updating) 题目汇总及部分答案(持续更新中) Leetcode problems clas ...

  6. leetcode hard

    # Title Solution Acceptance Difficulty Frequency     4 Median of Two Sorted Arrays       27.2% Hard ...

  7. LeetCode All in One 题目讲解汇总(转...)

    终于将LeetCode的免费题刷完了,真是漫长的第一遍啊,估计很多题都忘的差不多了,这次开个题目汇总贴,并附上每道题目的解题连接,方便之后查阅吧~ 如果各位看官们,大神们发现了任何错误,或是代码无法通 ...

  8. C#LeetCode刷题-数组

    数组篇 # 题名 刷题 通过率 难度 1 两数之和 C#LeetCode刷题之#1-两数之和(Two Sum) 43.1% 简单 4 两个排序数组的中位数 C#LeetCode刷题之#4-两个排序数组 ...

  9. C#LeetCode刷题-数学

    数学篇 # 题名 刷题 通过率 难度 2 两数相加   29.0% 中等 7 反转整数 C#LeetCode刷题之#7-反转整数(Reverse Integer) 28.6% 简单 8 字符串转整数 ...

随机推荐

  1. linux的ssh服务

    1.检查是否安装ssh > rpm -qa|grep ssh 2.安装ssh服务 > yum install ssh 配置 /etc/ssh/sshd_config 端口 22 3.启动s ...

  2. jQuery中animate()对Firefox无效的解决办法

    在使用 animate()做返回顶部的动画时,会出现对Firefox无效的情况,如: $('body').animate({scrollTop:'0'},500); 它对Chrome,IE,Opera ...

  3. sock基础编程介绍

    一个简单的python socket编程 一.套接字 套接字是为特定网络协议(例如TCP/IP,ICMP/IP,UDP/IP等)套件对上的网络应用程序提供者提供当前可移植标准的对象.它们允许程序接受并 ...

  4. Jmeter运行过程中如何让Fiddler同时可以抓获到服务器的应答报文

    在默认情况下,Jmeter运行过程中,Fiddler是抓不到对应的应答报文的. 但是,在某些时候,我们希望分析Jmeter执行失败的原因,想了解Jmeter获取到的应答报文是否有问题,就需要同服务器返 ...

  5. 06 Maven 聚合和继承

    Maven 聚合和继承 1. 聚合 2. 继承 <parent> <groupId>org.apache.karaf.demos</groupId> <art ...

  6. 创建cookie

    cookie的创建using System;using System.Collections.Generic;using System.Linq;using System.Web;using Syst ...

  7. 用pyqt5做一个能python程序能插入图片的ide

    之前只是放到github上了,现在一想应该开源,大家想继续做好这个ide的都能从这里起步. #注意在.py文件相同目录下放一个1.png做测试图片 #本质就是用html来实现图片 #写在前面的话:这个 ...

  8. for() 和$.each()的用法区别

    一.对于数组 var arr=['姚明','易建联','张继科']; $.each(arr,function(index,value){ document.write(index+"=&qu ...

  9. window.load 和$(document).ready() 、window.load和body onload区别

    1.执行时间 window.onload必须等到页面内包括图片的所有元素加载完毕后才能执行. $(document).ready()是DOM结构绘制完毕后就执行,不必等到加载完毕.2.编写个数不同 w ...

  10. Linux命令:sed

    简介 sed 是一种在线编辑器,它一次处理一行内容.处理时,把当前处理的行存储在临时缓冲区中,称为“模式空间”(pattern space),接着用sed命令处理缓冲区中的内容,处理完成后,把缓冲区的 ...