diff --git a/solution/0000-0099/0054.Spiral Matrix/README.md b/solution/0000-0099/0054.Spiral Matrix/README.md index 55bd25080ee84..d2023217ad7ca 100644 --- a/solution/0000-0099/0054.Spiral Matrix/README.md +++ b/solution/0000-0099/0054.Spiral Matrix/README.md @@ -360,6 +360,46 @@ func spiralOrder(matrix [][]int) (ans []int) { } ``` +### **Rust** + +```rust +impl Solution { + pub fn spiral_order(matrix: Vec>) -> Vec { + let mut x1 = 0; + let mut y1 = 0; + let mut x2 = matrix.len() - 1; + let mut y2 = matrix[0].len() - 1; + let mut result = vec![]; + + while x1 <= x2 && y1 <= y2 { + for j in y1..=y2 { + result.push(matrix[x1][j]); + } + for i in x1 + 1..=x2 { + result.push(matrix[i][y2]); + } + if x1 < x2 && y1 < y2 { + for j in (y1..y2).rev() { + result.push(matrix[x2][j]); + } + for i in (x1 + 1..x2).rev() { + result.push(matrix[i][y1]); + } + } + x1 += 1; + y1 += 1; + if x2 != 0 { + x2 -= 1; + } + if y2 != 0 { + y2 -= 1; + } + } + return result; + } +} +``` + ### **JavaScript** ```js diff --git a/solution/0000-0099/0054.Spiral Matrix/README_EN.md b/solution/0000-0099/0054.Spiral Matrix/README_EN.md index 2806b758b8bbf..768d4a2a0c47f 100644 --- a/solution/0000-0099/0054.Spiral Matrix/README_EN.md +++ b/solution/0000-0099/0054.Spiral Matrix/README_EN.md @@ -350,6 +350,46 @@ func spiralOrder(matrix [][]int) (ans []int) { } ``` +### **Rust** + +```rust +impl Solution { + pub fn spiral_order(matrix: Vec>) -> Vec { + let mut x1 = 0; + let mut y1 = 0; + let mut x2 = matrix.len() - 1; + let mut y2 = matrix[0].len() - 1; + let mut result = vec![]; + + while x1 <= x2 && y1 <= y2 { + for j in y1..=y2 { + result.push(matrix[x1][j]); + } + for i in x1 + 1..=x2 { + result.push(matrix[i][y2]); + } + if x1 < x2 && y1 < y2 { + for j in (y1..y2).rev() { + result.push(matrix[x2][j]); + } + for i in (x1 + 1..x2).rev() { + result.push(matrix[i][y1]); + } + } + x1 += 1; + y1 += 1; + if x2 != 0 { + x2 -= 1; + } + if y2 != 0 { + y2 -= 1; + } + } + return result; + } +} +``` + ### **JavaScript** ```js diff --git a/solution/0000-0099/0054.Spiral Matrix/Solution.rs b/solution/0000-0099/0054.Spiral Matrix/Solution.rs new file mode 100644 index 0000000000000..04eb1e7c3e013 --- /dev/null +++ b/solution/0000-0099/0054.Spiral Matrix/Solution.rs @@ -0,0 +1,35 @@ +impl Solution { + pub fn spiral_order(matrix: Vec>) -> Vec { + let mut x1 = 0; + let mut y1 = 0; + let mut x2 = matrix.len() - 1; + let mut y2 = matrix[0].len() - 1; + let mut result = vec![]; + + while x1 <= x2 && y1 <= y2 { + for j in y1..=y2 { + result.push(matrix[x1][j]); + } + for i in x1 + 1..=x2 { + result.push(matrix[i][y2]); + } + if x1 < x2 && y1 < y2 { + for j in (y1..y2).rev() { + result.push(matrix[x2][j]); + } + for i in (x1 + 1..x2).rev() { + result.push(matrix[i][y1]); + } + } + x1 += 1; + y1 += 1; + if x2 != 0 { + x2 -= 1; + } + if y2 != 0 { + y2 -= 1; + } + } + return result; + } +}