「力扣」第 542 題:01 矩陣(廣度優先遍歷)

地址:https://leetcode-cn.com/problems/01-matrix/

思路:

  • 最少步數,肯定使用廣度優先遍歷;
  • 使用隊列,0 是起點;
  • 原地填寫表格,所以一開始要把 1 賦值成爲一個負數。

參考題解:廣度優先遍歷(Java)

Java 代碼:

import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;


public class Solution {

    // 廣度優先遍歷

    public int[][] updateMatrix(int[][] matrix) {
        int rows = matrix.length;
        if (rows == 0) {
            return new int[0][0];
        }
        int cols = matrix[0].length;
        Queue<Integer> queue = new LinkedList<>();
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (matrix[i][j] == 0) {
                    // 從爲 0 的地方開始向外擴散
                    queue.add(getIndex(i, j, cols));
                } else {
                    // 設置成一個特殊值,說明當前這個座標的位置還沒有被擴散到
                    matrix[i][j] = -1;
                }
            }
        }

        int[][] directions = {{-1, 0}, {0, -1}, {0, 1}, {1, 0}};
        // 從爲 0 的地方開始進行廣度優先遍歷
        while (!queue.isEmpty()) {
            // 當前的位置,一開始的時候,"0" 正好,到"0" 的距離也是 0 ,符合題意
            Integer head = queue.poll();

            int currentX = head / cols;
            int currentY = head % cols;

            // 現在要往 4 個方向擴散
            for (int i = 0; i < 4; i++) {
                int newX = currentX + directions[i][0];
                int newY = currentY + directions[i][1];
                // 在有效的座標範圍內,並且還沒有被訪問過
                if (inArea(newX, newY, rows, cols) && matrix[newX][newY] == -1) {
                    matrix[newX][newY] = matrix[currentX][currentY] + 1;
                    queue.add(getIndex(newX, newY, cols));
                }
            }
        }
        return matrix;
    }

    /**
     * @param x    二維表格單元格橫座標
     * @param y    二維表格單元格縱座標
     * @param cols 二維表格列數
     * @return
     */
    private int getIndex(int x, int y, int cols) {
        return x * cols + y;
    }


    /**
     * @param x    二維表格單元格橫座標
     * @param y    二維表格單元格縱座標
     * @param rows 二維表格行數
     * @param cols 二維表格列數
     * @return
     */
    private boolean inArea(int x, int y, int rows, int cols) {
        return x >= 0 && x < rows && y >= 0 && y < cols;
    }

    public static void main(String[] args) {
        int[][] matrix = new int[][]{
                {0, 0, 0},
                {0, 1, 0},
                {1, 1, 1}
        };
        Solution solution = new Solution();
        int[][] res = solution.updateMatrix(matrix);
        for (int i = 0; i < res.length; i++) {
            System.out.println(Arrays.toString(res[i]));
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章