1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
/****************************************************************************************** ******************************************************************************************* Chapter 1 Arrays and Strings * Write an algorithm such that if an element in an M * N matrix is 0, * its entire row and column is set to 0; By: Hamed Kiani (July 20, 2015) ****************************************************************************************** ******************************************************************************************/ #include<iostream> #include<cstring> using namespace std; const int row = 3, col = 3; void print_mat(double **mat, int row, int col) { for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) cout << " " << mat[i][j]; cout << endl; } } // space O(n), time O(n^2) void zero_in_matrix(double **mat) { // int zero_row = (int) malloc(sizeof(int) * row) int zero_row[row] = {0}; //int *zero_row = (int*) malloc(sizeof(int) * row); // int zero_col = (int) malloc(sizeof(int) * col) int zero_col[col] = {0}; //int *zero_col = (int*) malloc(sizeof(int) * col); // keep the indices of zero values in mat for (int i = 0 ; i < row; i++) for (int j = 0 ; j < col; j++) { if (mat[i][j] == 0){ zero_row[i] = 1; zero_col[j] = 1; } } // che if there is a zero, change all values of the colum and row to zero for (int i = 0 ; i < row; i++) for (int j = 0 ; j < col; j++) { if ((zero_row[i] == 1) | (zero_col[j] == 1)) mat[i][j] = 0; } } void main() { double **mat; //int col, row; cout << " # or rows: " << row << endl; // cin >> row; cout << " # or cols: " << col << endl; // cin >> col; mat = (double **) malloc(sizeof(double *) * row); for (int i = 0; i < row; i++) mat[i] = (double *) malloc(sizeof(double) * col); for (int i = 0; i < row; i++) for (int j = 0; j < col; j++) cin >> mat[i][j]; cout << " the original matrix: " << endl; print_mat(mat, row, col); zero_in_matrix(mat); cout << " the matrix after zeroing: " << endl; print_mat(mat, row, col); } |
0 Comments
|
A place to practice the coding interview.
AuthorHamed Kiani Categories
All
Archives |