2D array practice question
unknown
java
a year ago
2.2 kB
97
Indexable
public boolean searchMatrix(int[][] matrix, int target) {
int n = matrix.length;
int m = matrix[0].length;
int row = 0; // n-1
int col = m-1; // 0
while(row<n && col>=0){
if(matrix[row][col] < target){
row++;
} else if(matrix[row][col] > target){
col--;
} else {
return true;
}
}
return false;
}
// only valid for square matrix
public int[][] transpose(int[][] matrix) {
int n = matrix.length;
int curr_r = 0;
int curr_c = 0;
while(curr_r<n){
int i = curr_r;
for(int j = curr_c; j<n; j++){
// swap row, col wit
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
curr_r++;
curr_c++;
}
return matrix;
}
public static void printSpiral(int[][] matrix){
int n = matrix.length;
int m = matrix[0].length;
int sr = 0, sc = 0, er = n-1, ec = m-1;
int row,col;
while(sr<=er && sc<=ec){
// print starting col from sr to er
col = sc;
for(row=sr; row<=er && sc<=ec; row++){
System.out.print(matrix[row][col] + ", ");
}
sc++;
// print ending row from sc to ec
row = er;
for(col = sc; col<=ec && sr<=er; col++){
System.out.print(matrix[row][col] + ", ");
}
er--;
// print ending col from er to sr
col = ec;
for(row=er; row>=sr && sr<=er && sc<=ec; row--){
System.out.print(matrix[row][col] + ", ");
}
ec--;
// print starting row from ec to sc
row = sr;
for(col = ec; col>=sc && sr<=er && sc<=ec; col--){
System.out.print(matrix[row][col] + ", ");
}
sr++;
System.out.println();
}
}
public static void main(String[] args){
int[][] arr = {{1,6,11,14,21}, {2,7,12,15,25}, {3,8,13,16,22}, {4,9,17,19,24}, {5,10,20,18,23}};
printSpiral(arr);
}Editor is loading...
Leave a Comment