17 lines
566 B
Rust
17 lines
566 B
Rust
|
// A solution using loops and still pretty
|
||
|
// easy to understand, and iterates over the
|
||
|
// matrix only once.
|
||
|
impl Solution {
|
||
|
pub fn matrix_reshape(mat: Vec<Vec<i32>>, r: i32, c: i32) -> Vec<Vec<i32>> {
|
||
|
let (m, n) = (mat.len(), mat[0].len());
|
||
|
let (r, c) = (r as usize, c as usize);
|
||
|
if m*n != r*c || m == r {
|
||
|
return mat;
|
||
|
}
|
||
|
let mut reshaped_matrix = vec![vec![0; c]; r];
|
||
|
for idx in (0..m*n) {
|
||
|
reshaped_matrix[idx / c][idx % c] = mat[idx / n][idx % n];
|
||
|
}
|
||
|
reshaped_matrix
|
||
|
}
|
||
|
}
|