01 Matrix

/*
 本算法答案由上岸科技提供。
 上岸科技是一个专致力于高效培养北美留学生拥有实际面试能力的团体。
 我们采用小班化线上,线下教学让学生更快,更好的学习到想要的知识。
 团队主要由一群怀揣情怀于美国高校毕业的一线IT公司工程师构成。
 我们坚信对于求职者算法并不是全部,合理的技巧加上适当的算法培训能够大大的提升求职成功概率也能大大减少刷题的痛苦。
 正如我们的信仰:我们教的是如何上岸而不仅是算法。
 更多信息请关注官网:https://www.shanganonline.com/
*/
class Solution {
    public int[][] updateMatrix(int[][] matrix) {
        int[] xBias = new int[]{0,0,-1,1};
        int[] yBias = new int[]{-1, 1, 0, 0};
        Queue<int[]> queue = new LinkedList<>();
        int[][] result = new int[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] == 0) {
                    queue.offer(new int[] {i, j});
                } else {
                    result[i][j] = -1;
                }
            }
        }
        int level = 1;
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                int[] current = queue.poll();
                for (int j = 0; j < xBias.length; j++) {
                    int newX = current[0] + xBias[j];
                    int newY = current[1] + yBias[j];
                    if (isValid(matrix, newX, newY)) {
                        if (result[newX][newY] == -1) {
                            queue.offer(new int[]{newX, newY});
                            result[newX][newY] = level;
                        }
                    }
                }
            }
            level++;
        }
        return result;
    }
    
    private boolean isValid(int[][] matrix, int newX, int newY) {
        return newX >= 0 && newY >= 0 && newX < matrix.length && newY < matrix[0].length;
    }
}

Last updated

Was this helpful?