您现在的位置是:首页 >技术杂谈 >算法leetcode|54. 螺旋矩阵(rust重拳出击)网站首页技术杂谈

算法leetcode|54. 螺旋矩阵(rust重拳出击)

二当家的白帽子 2024-09-01 12:01:03
简介算法leetcode|54. 螺旋矩阵(rust重拳出击)


54. 螺旋矩阵:

给你一个 mn 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。

样例 1:

输入:
	
	matrix = [[1,2,3],[4,5,6],[7,8,9]]
	
输出:
	
	[1,2,3,6,9,8,7,4,5]

样例 2:

输入:
	
	matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
	
输出:
	
	[1,2,3,4,8,12,11,10,9,5,6,7]

提示:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 10
  • -100 <= matrix[i][j] <= 100

分析:

  • 面对这道算法题目,二当家的陷入了沉思。
  • 可以每次循环移动一步,判断移到边界就变换方向。
  • 也可以每次循环都换完4次方向,也就是完成一次顺时针,然后缩圈。

题解:

rust:

impl Solution {
    pub fn spiral_order(matrix: Vec<Vec<i32>>) -> Vec<i32> {
        let mut ans = Vec::new();
        let (rows, columns) = (matrix.len(), matrix[0].len());
        let (mut left, mut right, mut top, mut bottom) = (0, columns - 1, 0, rows - 1);
        while left <= right && top <= bottom {
            (left..right + 1).for_each(|column| {
                ans.push(matrix[top][column]);
            });
            (top + 1..bottom + 1).for_each(|row| {
                ans.push(matrix[row][right]);
            });
            if left < right && top < bottom {
                (left..right).rev().for_each(|column| {
                    ans.push(matrix[bottom][column]);
                });
                (top + 1..bottom).rev().for_each(|row| {
                    ans.push(matrix[row][left]);
                });
            }
            if right == 0 || bottom == 0 {
                break;
            }
            left += 1;
            right -= 1;
            top += 1;
            bottom -= 1;
        }
        return ans;
    }
}

go:

func spiralOrder(matrix [][]int) []int {
    rows, columns := len(matrix), len(matrix[0])
	left, right, top, bottom := 0, columns-1, 0, rows-1
	ans := make([]int, rows*columns)
	index := 0

	for left <= right && top <= bottom {
		for column := left; column <= right; column++ {
			ans[index] = matrix[top][column]
			index++
		}
		for row := top + 1; row <= bottom; row++ {
			ans[index] = matrix[row][right]
			index++
		}
		if left < right && top < bottom {
			for column := right - 1; column >= left; column-- {
				ans[index] = matrix[bottom][column]
				index++
			}
			for row := bottom - 1; row > top; row-- {
				ans[index] = matrix[row][left]
				index++
			}
		}
		left++
		right--
		top++
		bottom--
	}

	return ans
}

c++:

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> ans;

        int rows = matrix.size(), columns = matrix[0].size();
        int left = 0, right = columns - 1, top = 0, bottom = rows - 1;
        while (left <= right && top <= bottom) {
            for (int column = left; column <= right; ++column) {
                ans.emplace_back(matrix[top][column]);
            }
            for (int row = top + 1; row <= bottom; ++row) {
                ans.emplace_back(matrix[row][right]);
            }
            if (left < right && top < bottom) {
                for (int column = right - 1; column >= left; --column) {
                    ans.emplace_back(matrix[bottom][column]);
                }
                for (int row = bottom - 1; row > top; --row) {
                    ans.emplace_back(matrix[row][left]);
                }
            }
            ++left;
            --right;
            ++top;
            --bottom;
        }

        return ans;
    }
};

python:

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        ans = list()
        rows, columns = len(matrix), len(matrix[0])
        left, right, top, bottom = 0, columns - 1, 0, rows - 1
        while left <= right and top <= bottom:
            for column in range(left, right + 1):
                ans.append(matrix[top][column])
            for row in range(top + 1, bottom + 1):
                ans.append(matrix[row][right])
            if left < right and top < bottom:
                for column in range(right - 1, left - 1, -1):
                    ans.append(matrix[bottom][column])
                for row in range(bottom - 1, top, -1):
                    ans.append(matrix[row][left])
            left, right, top, bottom = left + 1, right - 1, top + 1, bottom - 1
        return ans


java:

每次循环移动一步:

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> ans = new ArrayList<Integer>();

        final int     rows             = matrix.length, columns = matrix[0].length;
        int           left             = 0, right = columns - 1, top = 0, bottom = rows - 1;
        final int     total            = rows * columns;
        int           row              = 0, column = 0;
        final int[][] moveDirections   = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        final int[][] borderDirections = {{1, 0, 0, 0}, {0, 0, 1, 0}, {0, -1, 0, 0}, {0, 0, 0, -1}};
        int           directionIndex   = 0;
        for (int i = 0; i < total; i++) {
            ans.add(matrix[row][column]);
            int nextRow = row + moveDirections[directionIndex][0], nextColumn = column + moveDirections[directionIndex][1];
            if (nextRow < top || nextRow > bottom || nextColumn < left || nextColumn > right) {
                // 变换方向
                directionIndex = (directionIndex + 1) % 4;
                // 修改边界
                left += borderDirections[directionIndex][0];
                right += borderDirections[directionIndex][1];
                top += borderDirections[directionIndex][2];
                bottom += borderDirections[directionIndex][3];
            }
            row += moveDirections[directionIndex][0];
            column += moveDirections[directionIndex][1];
        }

        return ans;
    }
}

每次循环完成一个顺时针:

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> ans = new ArrayList<Integer>();

        final int rows = matrix.length, columns = matrix[0].length;
        int       left = 0, right = columns - 1, top = 0, bottom = rows - 1;
        while (left <= right && top <= bottom) {
            for (int column = left; column <= right; ++column) {
                ans.add(matrix[top][column]);
            }
            for (int row = top + 1; row <= bottom; ++row) {
                ans.add(matrix[row][right]);
            }
            if (left < right && top < bottom) {
                for (int column = right - 1; column >= left; --column) {
                    ans.add(matrix[bottom][column]);
                }
                for (int row = bottom - 1; row > top; --row) {
                    ans.add(matrix[row][left]);
                }
            }
            ++left;
            --right;
            ++top;
            --bottom;
        }

        return ans;
    }
}

非常感谢你阅读本文~
欢迎【点赞】【收藏】【评论】~
放弃不难,但坚持一定很酷~
希望我们大家都能每天进步一点点~
本文由 二当家的白帽子:https://le-yi.blog.csdn.net/ 博客原创~


风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。