变为棋盘
class Solution { public int movesToChessboard(int[][] board) { int xlen = board.length; int ylen = board[0].length; int xsum = 0; int ysum = 0; int[] errors = new int[2]; int cur = 0; int k = -1; int t = -1; for(int i=0;i<xlen;++i){ xsum += board[i][0]; } for(int i=0;i<ylen;++i){ ysum += board[0][i]; } if(((xlen%2==0&&2*xsum==xlen)||(xlen%2!=0&&(2*xsum-1==xlen||2*xsum+1==xlen)))&& ((ylen%2==0&&2*ysum==ylen)||(ylen%2!=0&&(2*ysum-1==ylen||2*ysum+1==ylen)))){ for(int i=0;i<xlen;++i){ if(k==-1&&board[i][0]==0){ k = i; if(t!=-1){ for(int j=0;j<ylen;++j){ if(board[k][j]+board[t][j]!=1){ return -1; } } } } if(t==-1&&board[i][0]==1){ t = i; if(k!=-1){ for(int j=0;j<ylen;++j){ if(board[k][j]+board[t][j]!=1){ return -1; } } } } if(k!=-1&&board[i][0]==0){ for(int j=0;j<ylen;++j){ if(board[k][j]!=board[i][j]){ return -1; } } } if(t!=-1&&board[i][0]==1){ for(int j=0;j<ylen;++j){ if(board[t][j]!=board[i][j]){ return -1; } } } } }else { return -1; } //上面是判断,下面是计算 t=0; k=0; cur=0; for(int i=0;i<xlen;++i) { if(board[i][0]==cur) { ++t; }else { ++k; } cur=1-cur; } if(t%2!=0) { errors[0]=k/2; }else if(k%2!=0){ errors[0]=t/2; }else{ errors[0]=Math.min(k, t)/2; } t=0; k=0; cur=0; for(int i=0;i<ylen;++i) { if(board[0][i]==cur) { ++t; }else { ++k; } cur = 1-cur; } if(k%2!=0) { errors[1]=t/2; }else if(t%2!=0) { errors[1]=k/2; }else { errors[1]=Math.min(k, t)/2; } return errors[0]+errors[1]; } }