| 70 | return false; |
| 71 | } |
| 72 | public static void commonElements(int Mat[][], int r, int c) |
| 73 | { |
| 74 | // pick one by one element of the first row and check if they are present in all rows. |
| 75 | for(int firstRow=0;firstRow<c;firstRow++) |
| 76 | { |
| 77 | // pick element |
| 78 | int element=Mat[0][firstRow]; |
| 79 | // if duplicate then skip the element |
| 80 | if(seen(Mat[0],element,firstRow)) continue; |
| 81 | // variable for tracking rows. |
| 82 | int count=0; |
| 83 | // if element is not present in anyone of the row then skip the element. |
| 84 | int flag=0; |
| 85 | // traverse from 1st to last row |
| 86 | for(int row=1;row<r;row++) |
| 87 | { |
| 88 | for(int col=0;col<c;col++) |
| 89 | { |
| 90 | // if element is found then increment the counter |
| 91 | if(element==Mat[row][col]) |
| 92 | { |
| 93 | count++; |
| 94 | // if present in last row and count is equal to row-1, then print it |
| 95 | if(row==r-1 && count==r-1) |
| 96 | System.out.println(element); |
| 97 | // if count is same as row then break to avoid adding duplicates |
| 98 | else if(row!=r-1 && count==row) |
| 99 | break; |
| 100 | // if element not present in the current row then set flag to 1, |
| 101 | else |
| 102 | { |
| 103 | flag=1; |
| 104 | break; |
| 105 | } |
| 106 | } |
| 107 | } |
| 108 | // break the outer loop and check for next element. |
| 109 | if(flag==1) break; |
| 110 | } |
| 111 | } |
| 112 | } |
| 113 | } |