原文
Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column are set to 0.
译文
写一个算法,如果一个MxN中的一个元素为0,那么将这个元素所在的行和列都设置为0。
解答
遍历一次矩阵,当遇到元素等于0时,记录下这个元素对应的行和列。并设置一个标记。在遍历完之后,再根据之前的标记设置矩阵的值。
import java.util.BitSet; public class Main { public static void setZero(int[][] mat, int m, int n) { BitSet lineFlag = new BitSet(); BitSet rowFlag = new BitSet(); for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { if(mat[i][j] == 0) { lineFlag.set(i); rowFlag.set(j); } } } for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { if(lineFlag.get(i) || rowFlag.get(j)) { mat[i][j] = 0; } } } } public static void main(String args[]) { int a[][] = { { 1, 2, 3, 4 }, { 5, 6, 0, 8 }, { 9, 0, 11, 12 }, { 13, 14, 15, 16 } }; for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) System.out.print(a[i][j] + " "); System.out.println(); } setZero(a, 4, 4); System.out.println("------------------"); for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) System.out.print(a[i][j] + " "); System.out.println(); } } }