注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号
x
本帖最后由 匿名 于 2021-9-17 12:03 编辑
店面 华人
和LC 散而就 类似但是 求的是相同数字构成的最长path
我开法 请share 思路
如果对您后面面试有帮助 求赐米- static int[][] d4 = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
- static int m, n;
- public static int longestPathWithSameValue(int[][] A) {
- int max = 0;
- m = A.length;
- n = A[0].length;
- for (int i = 0; i < m; i++) {
- for (int j = 0; j < n; j++) {
- boolean[][] vis = new boolean[A.length][A[0].length];
- max = Math.max(max, f(A, vis, i, j, A[i][j]));
- }
- }
- return max;
- }
- /*
- Note "You may not move diagonally or move outside the boundary (i.e., wrap-around is not
- allowed)."
- so it is not sum += f(A, vis, r, c, v);
- */
- private static int f(int[][] A, boolean[][] vis, int i, int j, int v) {
- vis[i][j] = true;
- int max = 1;
- for (int[] d : d4) {
- int r = i + d[0], c = j + d[1];
- if (r >= 0 && c >= 0 && r < m && c < n && !vis[r][c] && A[r][c] == v)
- max = Math.max(max, 1 + f(A, vis, r, c, v));
- }
- vis[i][j] = false;
- return max;
- }
- // ==========================================================================
- public static void main(String[] args) {
- int[][] matrix =
- (new int[][] {
- {7, 9, 6},
- {9, 9, 9},
- {2, 9, 1}
- });
- System.out.println(longestPathWithSameValue(matrix) == 3);
- matrix =
- new int[][] {
- {1, 1, 1, 2, 4},
- {5, 1, 5, 3, 1},
- {3, 4, 2, 1, 1}
- };
- System.out.println(longestPathWithSameValue(matrix) == 3);
- matrix =
- new int[][] {
- {9, 9, 9, 9, 9, 9, 9},
- {9, 9, 8, 9, 9, 9, 9},
- {9, 9, 9, 12, 9, 9, 9},
- {9, 9, 9, 12, 9, 9, 9},
- {9, 9, 9, 12, 9, 9, 9},
- {9, 9, 9, 12, 9, 9, 9}
- }; // 37
- System.out.println(longestPathWithSameValue(matrix) == 37);
- matrix =
- new int[][] {
- {1, 3, 1, 1},
- {0, 0, 5, 1},
- {0, 0, 5, 5}
- };
- System.out.println(longestPathWithSameValue(matrix) == 4);
- matrix =
- new int[][] {
- {1, 3, 1, 1},
- {5, 5, 5, 1},
- {5, 5, 5, 5}
- };
- System.out.println(longestPathWithSameValue(matrix) == 7);
- matrix =
- new int[][] {
- {1, 1, 1, 3, 2},
- {2, 1, 1, 4, 2},
- {3, 3, 1, 1, 1},
- {4, 4, 4, 3, 4}
- };
- System.out.println(longestPathWithSameValue(matrix) == 7);
- }
复制代码 |