题目地址:
https://www.lintcode.com/problem/sliding-puzzle-iii/description
问一个八数码问题是否有解。
先将矩阵的三行依次拼接排成一行,然后算一下除了 0 0 0之外的数的逆序对数目即可。如果逆序对数目是偶数则输出“YES”,否则“NO”。参考https://blog.csdn.net/qq_46105170/article/details/108314218。代码如下:
public class Solution {
/**
* @param matrix: The 3*3 matrix
* @return: The answer
*/
public String jigsawPuzzle(int[][] matrix) {
// Write your code here
return (computeInversePairs(matrix) & 1) == 0 ? "YES" : "NO";
}
private int computeInversePairs(int[][] matrix) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
sb.append(matrix[i][j]);
}
}
int count = 0;
for (int i = 1; i < sb.length(); i++) {
for (int j = 0; j < i; j++) {
if (sb.charAt(i) == '0' || sb.charAt(j) == '0') {
continue;
}
if (sb.charAt(j) > sb.charAt(i)) {
count++;
}
}
}
return count;
}
}
时空复杂度 O ( 1 ) O(1) O(1)。