83 lines
1.8 KiB
C
83 lines
1.8 KiB
C
|
#include <stdio.h>
|
||
|
#include <assert.h>
|
||
|
#include <stdlib.h>
|
||
|
|
||
|
typedef struct {
|
||
|
int ** data;
|
||
|
int size;
|
||
|
} Matrix;
|
||
|
|
||
|
Matrix matCreate(int size) {
|
||
|
int** data = malloc(sizeof(int*) * size);
|
||
|
for(unsigned int row = 0; row < size; row++) data[row] = malloc(sizeof(int)*size);
|
||
|
return (Matrix){data,size};
|
||
|
}
|
||
|
|
||
|
void matSet(Matrix m, size_t row, size_t col, int v) {
|
||
|
assert(row < m.size);
|
||
|
assert(col < m.size);
|
||
|
m.data[row][col] = v;
|
||
|
}
|
||
|
|
||
|
int matGet(Matrix m, size_t row, size_t col) {
|
||
|
assert(row < m.size);
|
||
|
assert(col < m.size);
|
||
|
return m.data[row][col];
|
||
|
}
|
||
|
|
||
|
void matSwapRows(Matrix m, size_t row1, size_t row2) {
|
||
|
assert(row1 < m.size);
|
||
|
assert(row2 < m.size);
|
||
|
int* tmp = m.data[row1];
|
||
|
m.data[row1] = m.data[row2];
|
||
|
m.data[row2] = tmp;
|
||
|
}
|
||
|
|
||
|
void matPrint(Matrix m) {
|
||
|
for(unsigned int row = 0; row < m.size; row++) {
|
||
|
for(unsigned int col = 0; col < m.size; col++) {
|
||
|
printf("%02d ", matGet(m,row,col));
|
||
|
}
|
||
|
printf("\n");
|
||
|
}
|
||
|
}
|
||
|
|
||
|
void matFree(Matrix m) {
|
||
|
for(unsigned int row = 0; row < m.size; row++) free(m.data[row]);
|
||
|
free(m.data);
|
||
|
}
|
||
|
|
||
|
int reorder_mat(Matrix m, int rowCol) {
|
||
|
if(rowCol >= m.size) return 1;
|
||
|
if(matGet(m,rowCol,rowCol) != 0) return reorder_mat(m,rowCol+1);
|
||
|
|
||
|
for(int candidate = rowCol+1; candidate < m.size; candidate++) {
|
||
|
if(matGet(m,candidate, rowCol) != 0) {
|
||
|
matSwapRows(m, rowCol, candidate);
|
||
|
if(reorder_mat(m, rowCol+1)) return 1;
|
||
|
matSwapRows(m, rowCol, candidate);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return 0;
|
||
|
}
|
||
|
|
||
|
int main( int argc, char *argv[] ) {
|
||
|
|
||
|
Matrix m = matCreate(2);
|
||
|
matSet(m,0,0,0);
|
||
|
matSet(m,0,1,1);
|
||
|
matSet(m,1,0,1);
|
||
|
matSet(m,1,1,0);
|
||
|
|
||
|
matPrint(m);
|
||
|
|
||
|
if(!reorder_mat(m,0)) {
|
||
|
printf("Failed\n");
|
||
|
}
|
||
|
|
||
|
matPrint(m);
|
||
|
|
||
|
return 0;
|
||
|
}
|