|
| 1 | +impl Solution { |
| 2 | + pub fn moves_to_chessboard(board: Vec<Vec<i32>>) -> i32 { |
| 3 | + let n = board.len(); |
| 4 | + |
| 5 | + for i in 0..n { |
| 6 | + for j in 0..n { |
| 7 | + if board[0][0] ^ board[i][0] ^ board[0][j] ^ board[i][j] == 1 { |
| 8 | + return -1; |
| 9 | + } |
| 10 | + } |
| 11 | + } |
| 12 | + |
| 13 | + let [mut row_sum, mut col_sum, mut row_misplaced, mut col_misplaced] = [0, 0, 0, 0]; |
| 14 | + for i in 0..n { |
| 15 | + row_sum += board[0][i]; |
| 16 | + col_sum += board[i][0]; |
| 17 | + |
| 18 | + if board[i][0] == i as i32 % 2 { |
| 19 | + row_misplaced += 1; |
| 20 | + } |
| 21 | + if board[0][i] == i as i32 % 2 { |
| 22 | + col_misplaced += 1; |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + let n = n as i32; |
| 27 | + if row_sum != n / 2 && row_sum != (n + 1) / 2 { |
| 28 | + return -1; |
| 29 | + } |
| 30 | + if col_sum != n / 2 && col_sum != (n + 1) / 2 { |
| 31 | + return -1; |
| 32 | + } |
| 33 | + |
| 34 | + if n % 2 == 1 { |
| 35 | + if col_misplaced % 2 == 1 { |
| 36 | + col_misplaced = n - col_misplaced; |
| 37 | + } |
| 38 | + if row_misplaced % 2 == 1 { |
| 39 | + row_misplaced = n - row_misplaced; |
| 40 | + } |
| 41 | + } else { |
| 42 | + col_misplaced = i32::min(n - col_misplaced, col_misplaced); |
| 43 | + row_misplaced = i32::min(n - row_misplaced, row_misplaced); |
| 44 | + } |
| 45 | + |
| 46 | + (col_misplaced + row_misplaced) / 2 |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +struct Solution {} |
| 51 | + |
| 52 | +#[cfg(test)] |
| 53 | +mod tests { |
| 54 | + use super::*; |
| 55 | + use crate::vec_vec_i32; |
| 56 | + |
| 57 | + #[test] |
| 58 | + fn test_moves_to_chessboard() { |
| 59 | + assert_eq!(Solution::moves_to_chessboard(vec_vec_i32![[0, 1, 1, 0], [0, 1, 1, 0], [1, 0, 0, 1], [1, 0, 0, 1]]), 2); |
| 60 | + } |
| 61 | + |
| 62 | + #[test] |
| 63 | + fn test_moves_to_chessboard2() { |
| 64 | + assert_eq!(Solution::moves_to_chessboard(vec_vec_i32![[0, 1], [1, 0]]), 0); |
| 65 | + } |
| 66 | + |
| 67 | + #[test] |
| 68 | + fn test_moves_to_chessboard3() { |
| 69 | + assert_eq!(Solution::moves_to_chessboard(vec_vec_i32![[1, 0], [1, 0]]), -1); |
| 70 | + } |
| 71 | +} |
0 commit comments