高级农民
- 积分
- 2296
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2015-8-24
- 最后登录
- 1970-1-1
|
- public class ConnectOne {
- int[][] DIRS = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
- public List<List<Integer>> solution(int[][] matrix) {
- Set<Integer> resSet = new HashSet<>();
- List<List<Integer>> res = new LinkedList<>();
- boolean[][] visitedOne = new boolean[matrix.length][matrix[0].length];
- for (int i = 0; i < matrix.length; i++) {
- for (int j = 0; j < matrix[0].length; j++) {
- if (matrix[i][j] == 1 && !visitedOne[i][j]) {
- helper(resSet, matrix, i, j, new boolean[matrix.length][matrix[0].length], visitedOne, 0);
- }
- }
- }
- for (int idx : resSet) {
- res.add(Arrays.asList(idx / matrix[0].length, idx % matrix[0].length));
- }
- return res;
- }
- private void helper(Set<Integer> resSet, int[][] matrix, int row, int col, boolean[][] curVisited, boolean[][] visitedOne, int len) {
- if (row < 0 || row >= matrix.length || col < 0 || col >= matrix[0].length || matrix[row][col] == -1 || curVisited[row][col]) {
- return;
- }
- resSet.add(row * matrix[0].length + col);
- if (matrix[row][col] == 1) {
- visitedOne[row][col] = true;
- if (len != 0) {
- return;
- }
- }
- curVisited[row][col] = true;
- for (int[] dir : DIRS) {
- int newRow = row + dir[0];
- int newCol = col + dir[1];
- helper(resSet, matrix, newRow, newCol, curVisited, visitedOne, len + 1);
- }
- curVisited[row][col] = false;
- }
- public static void main(String[] args) {
- ConnectOne solution = new ConnectOne();
- int[][] matrix = {{1, 0, -1, -1, 1}, {0, 0, 1, -1, 0}, {0, 1, -1, -1, 0}, {-1, -1, -1, -1, 1}};
- List<List<Integer>> resSet = solution.solution(matrix);
- int[][] printMatrix = new int[matrix.length][matrix[0].length];
- for (List<Integer> list : resSet) {
- printMatrix[list.get(0)][list.get(1)] = 1;
- }
- for (int i = 0; i < printMatrix.length; i++) {
- for (int j = 0; j < printMatrix[0].length; j++) {
- System.out.print(printMatrix[i][j] + ",");
- }
- System.out.println();
- }
- }
- }
复制代码 |
|