My solution is that we first assume that all columns have 1s, then we go through the rows, over the possible solutions that we have, and cut the columns that cannot be the solution.
This solution is written in Java:
Solution 1: O (n ^ 2) is straightforward
public class Main { // Given A: an M x N matrix public static ArrayList<Integer> solve (Integer [][] matrix) { // Assuming all columns have 1s, we have list S ArrayList<Integer> S = new ArrayList<Integer>(); // S = { 1, 2, .., N } for (int i=0; i < matrix[0].length; i++) { S.add(i); } // For Row i: 1..M for (Integer i = 0; i < matrix.length; i++) { // For Column j in list S for (Integer j : S) { if (matrix[i][j] != 1) { S.remove(j); } } } return S; } public static void main (String [] args) { int [][] matrix = { {1,1,1}, {0,1,1}, {0,0,1}, }; ArrayList<Integer> columns = solve (matrix); System.out.print(" columns that have 1s are: "); for (Integer n : columns) System.out.print(n+" "); } }
Solution 2: O (n) using a personalized data structure
private class Column { public ArrayList<Integer> data; public int count; public Column () { data = new ArrayList<Integer>(); count = 0; } public void add (int val) { data.add(val); count += val; } } public class Main { public static void main (String [] args) { Column [] matrix = { new Column (), new Column (), new Column () }; matrix[0].add(1); matrix[0].add(0); matrix[0].add(0); matrix[1].add(1); matrix[1].add(1); matrix[1].add(0); matrix[2].add(1); matrix[2].add(1); matrix[2].add(1); System.out.print(" columns that have 1s are: "); for (Column column : matrix) { if (column.count == column.data.size()) System.out.print(n+" "); } } }
source share