diff --git a/notes/剑指 offer 题解.md b/notes/剑指 offer 题解.md index 9e7e6d94..01f25e6a 100644 --- a/notes/剑指 offer 题解.md +++ b/notes/剑指 offer 题解.md @@ -624,26 +624,33 @@ private char[][] buildMatrix(char[] array) { ```java private int cnt = 0; private int[][] next = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}}; +private int rows; +private int cols; +private int threshold; private int[][] digitSum; public int movingCount(int threshold, int rows, int cols) { - initDigitSum(rows, cols); - dfs(new boolean[rows][cols], threshold, rows, cols, 0, 0); + this.rows = rows; + this.cols = cols; + this.threshold = threshold; + initDigitSum(); + boolean[][] hasVisited = new boolean[rows][cols]; + dfs(hasVisited, 0, 0); return cnt; } -private void dfs(boolean[][] visited, int threshold, int rows, int cols, int r, int c) { - if (r < 0 || r >= rows || c < 0 || c >= cols) return; - if (visited[r][c]) return; - visited[r][c] = true; - if (this.digitSum[r][c] > threshold) return; +private void dfs(boolean[][] hasVisited, int r, int c) { + if (r < 0 || r >= this.rows || c < 0 || c >= this.cols) return; + if (hasVisited[r][c]) return; + hasVisited[r][c] = true; + if (this.digitSum[r][c] > this.threshold) return; this.cnt++; for (int i = 0; i < this.next.length; i++) { - dfs(visited, threshold, rows, cols, r + next[i][0], c + next[i][1]); + dfs(hasVisited, r + next[i][0], c + next[i][1]); } } -private void initDigitSum(int rows, int cols) { +private void initDigitSum() { int[] digitSumOne = new int[Math.max(rows, cols)]; for (int i = 0; i < digitSumOne.length; i++) { int n = i; @@ -653,8 +660,8 @@ private void initDigitSum(int rows, int cols) { } } this.digitSum = new int[rows][cols]; - for (int i = 0; i < rows; i++) { - for (int j = 0; j < cols; j++) { + for (int i = 0; i < this.rows; i++) { + for (int j = 0; j < this.cols; j++) { this.digitSum[i][j] = digitSumOne[i] + digitSumOne[j]; } }