在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ An N x N What is the minimum number of moves to transform the board into a "chessboard" - a board where no 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:
一个 N x N的 输出将这个矩阵变为 “棋盘” 所需的最小移动次数。“棋盘” 是指任意一格的上下左右四个方向的值均与本身不同的矩阵。如果不存在可行的变换,输出 -1。 示例: 输入: board = [[0,1,1,0],[0,1,1,0],[1,0,0,1],[1,0,0,1]] 输出: 2 解释: 一种可行的变换方式如下,从左到右: 0110 1010 1010 0110 --> 1010 --> 0101 1001 0101 1010 1001 0101 0101 第一次移动交换了第一列和第二列。 第二次移动交换了第二行和第三行。 输入: board = [[0, 1], [1, 0]] 输出: 0 解释: 注意左上角的格值为0时也是合法的棋盘,如: 01 10 也是合法的棋盘. 输入: board = [[1, 0], [1, 0]] 输出: -1 解释: 任意的变换都不能使这个输入变为合法的棋盘。 提示:
Runtime: 52 ms
Memory Usage: 18.7 MB
1 class Solution { 2 func movesToChessboard(_ board: [[Int]]) -> Int { 3 var n:Int = board.count 4 var rowSum:Int = 0 5 var colSum:Int = 0 6 var rowDiff:Int = 0 7 var colDiff:Int = 0 8 for i in 0..<n 9 { 10 for j in 0..<n 11 { 12 if board[0][0] ^ board[i][0] ^ board[0][j] ^ board[i][j] != 0 13 { 14 return -1 15 } 16 } 17 } 18 for i in 0..<n 19 { 20 rowSum += board[0][i] 21 colSum += board[i][0] 22 rowDiff += (board[i][0] == i % 2 ? 1 : 0) 23 colDiff += (board[0][i] == i % 2 ? 1 : 0) 24 } 25 if n / 2 > rowSum || rowSum > (n + 1) / 2 {return -1} 26 if n / 2 > colSum || colSum > (n + 1) / 2 {return -1} 27 if n % 2 != 0 28 { 29 if rowDiff % 2 != 0 {rowDiff = n - rowDiff} 30 if colDiff % 2 != 0 {colDiff = n - colDiff} 31 } 32 else 33 { 34 rowDiff = min(n - rowDiff, rowDiff) 35 colDiff = min(n - colDiff, colDiff) 36 } 37 return (rowDiff + colDiff) / 2 38 } 39 }
|
请发表评论