Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 開發入門

演算法實作:把二維矩陣中包含 0 的元素,其所在列與行全部歸零

編輯:開發入門

這是一個經典的矩陣題目:給定一個二維整數矩陣,找出所有數值為 0 的元素,並把這些 0 所在的「列」與「行」上所有元素都改成 0。本範例用 Java 實作,示範如何先收集位置、再統一替換。

解題思路

直覺的做法有兩種。最簡單的是直接遍歷,遇到 0 就立刻把整列整行掃過一遍改成 0——但這會有副作用:原本不是 0 的元素被改成 0 之後,後續掃描會誤判它為「原始資料中的 0」,導致結果錯誤。

因此正確作法是兩階段處理:第一階段只負責掃描並記錄所有 0 的位置(用一個集合存放座標),第二階段再依這些座標統一替換。為了讓位置資訊清楚表達,我們另外定義一個小類別,用 x 代表列號、y 代表行號。

程式碼

import java.util.ArrayList;

// 找出二維矩陣中為 0 元素的所有集合
// 將矩陣中為 0 的元素的列與行全部替換為 0

public class MatrixZero {

    public static void main(String[] args) {
        int[][] a = {
            {1, 2, 3, 4, 5},
            {1, 2, 3, 4, 0},
            {0, 1, 2, 3, 4},
            {1, 2, 3, 4, 5}
        };

        int row = a.length;
        int col = a[0].length;

        // 第一階段:收集所有為 0 的位置
        ArrayList list = new ArrayList();
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (a[i][j] == 0) {
                    list.add(new Position(i, j));
                }
            }
        }

        System.out.println("The position of zero are:");
        for (int i = 0; i < list.size(); i++) {
            Position p = (Position) list.get(i);
            System.out.println("(" + p.getX() + "," + p.getY() + ")");
        }

        System.out.println("Before replace the Matrix is:");
        printMatrix(a);

        // 第二階段:依位置把整列與整行歸零
        for (int i = 0; i < list.size(); i++) {
            Position p = (Position) list.get(i);
            for (int k = 0; k < a[0].length; k++) {
                a[p.getX()][k] = 0;   // 該列全部歸零
            }
            for (int k = 0; k < a.length; k++) {
                a[k][p.getY()] = 0;   // 該行全部歸零
            }
        }

        System.out.println("After replace the Matrix is:");
        printMatrix(a);
    }

    // 列印二維矩陣的函式
    public static void printMatrix(int[][] a) {
        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < a[0].length; j++) {
                System.out.print(a[i][j] + "\t");
            }
            System.out.println();
        }
    }
}

// 定義一個類別,用來存放為 0 元素的位置
// x 代表在第幾列,y 代表在第幾行
class Position {
    private int x;
    private int y;

    public Position(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int getX() { return x; }
    public int getY() { return y; }
}

執行結果

The position of zero are:
(1,4)
(2,0)

Before replace the Matrix is:
1	2	3	4	5
1	2	3	4	0
0	1	2	3	4
1	2	3	4	5

After replace the Matrix is:
0	2	3	4	0
0	0	0	0	0
0	0	0	0	0
0	2	3	4	0

可以驗證:位置 (1,4) 使第 1 列與第 4 行全歸零,位置 (2,0) 使第 2 列與第 0 行全歸零,兩者合併後正好是輸出的樣子。

若進一步優化空間,可以改用兩個布林陣列分別記錄「哪些列有 0」與「哪些行有 0」,就能省下存放座標集合的空間,把額外空間從 O(k) 降到 O(m+n)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved