Query And Matrix
Send Feedback
You are given a binary matrix with ‘M’ rows and ‘N’ columns initially consisting of all 0s. 'Q' queries follow. The queries can be of 4 types:
Note:
Example :
Input Format:
Output Format:
Note:
Constraints:
Sample Input 1:
Sample Output 1:
Explanation of Sample Output 1:
Sample Input 2:
Sample Output 2:
Explanation of Sample Output 2:
code for this
public class Solution {
public static int[] query(int[][] mat, int m, int n, String[] q) {
int k = 0;
for (int i = 0; i < q.length; i++) {
String query = q[i];
int queryType = query.charAt(0) - '0';
if (queryType == 2) {
k++;
}
}
int[] result = new int[k];
int j = 0;
for (int i = 0; i < q.length; i++) {
String query = q[i];
int queryType = query.charAt(0) - '0';
char dimension = query.charAt(1);
int index = query.charAt(2) - '0';
if (queryType == 1) {
if (dimension == 'R') {
flipRow(mat, index, n);
} else if (dimension == 'C') {
flipColumn(mat, index, m);
}
} else if (queryType == 2) {
int count = 0;
if (dimension == 'R') {
count = countZeroInRow(mat, index, n);
} else if (dimension == 'C') {
count = countZeroInColumn(mat, index, m);
}
result[j] = count;
j++;
}
}
return result;
}
private static void flipRow(int[][] matrix, int rowIndex, int n) {
for (int j = 0; j < n; j++) {
matrix[rowIndex][j] ^= 1;
}
}
private static void flipColumn(int[][] matrix, int colIndex, int m) {
for (int i = 0; i < m; i++) {
matrix[i][colIndex] ^= 1;
}
}
private static int countZeroInRow(int[][] matrix, int rowIndex, int n) {
int count = 0;
for (int j = 0; j < n; j++) {
if (matrix[rowIndex][j] == 0) {
count++;
}
}
return count;
}
private static int countZeroInColumn(int[][] matrix, int colIndex, int m) {
int count = 0;
for (int i = 0; i < m; i++) {
if (matrix[i][colIndex] == 0) {
count++;
}
}
return count;
}
}
Comments
Post a Comment