public class Solution { private boolean[][] visited = new boolean[3][3]; private int m; private int n; public int numberOfPatterns(int m, int n) { if (n == 0 || m > n) { return 0; } int result = 0; this.m = m; this.n = n; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { visited[i][j] = true; result += getPattern(i, j, 1); visited[i][j] = false; } } return result; } private int getPattern(int x, int y, int level) { if (level > n) { return 0; } int result = level >= m ? 1 : 0; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (visited[i][j] || x == i && Math.abs(y - j) == 2 && !visited[i][1] || y == j && Math.abs(x - i) == 2 && !visited[1][j] || Math.abs(x - i) == 2 && Math.abs(y - j) == 2 && !visited[1][1]) { continue; } visited[i][j] = true; result += getPattern(i, j, level + 1); visited[i][j] = false; } } return result; } }
1. 3x3 pattern board. Do not mess it up.
2. pattern counting start from 1, not 0
时间: 2024-10-07 02:39:22