Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

https://leetcode.cn/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/description/

Image Added

题解:https://leetcode.cn/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/solutions/129360/mian-shi-ti-29-shun-shi-zhen-da-yin-ju-zhen-she-di/

Code Block
languagecpp
class Solution 
{
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) 
    {
        if (matrix.empty()) return {};
        vector<int> res;
        int l = 0;                      //左边界
        int r = matrix[0].size() - 1;   //右边界
        int t = 0;                      //上边界
        int b = matrix.size() - 1;      //下边界
        while (true)
        {
            //left -> right
            for (int i = l; i <= r; i++) res.push_back(matrix[t][i]);
            if (++t > b) break;
            //top -> bottom
            for (int i = t; i <= b; i++) res.push_back(matrix[i][r]);
            if (--r < l) break;
            //right -> left
            for (int i = r; i >= l; i--) res.push_back(matrix[b][i]);
            if (--b < t) break;
            //bottom -> top
            for (int i = b; i >= t; i--) res.push_back(matrix[i][l]);
            if (++l > r) break;
        }
        return res;
    }
};

Image Added

Code Block
languagego
package main

import "fmt"

func printMatrix(matrix [][]int) {
	var (
		l = 0                  // 左边界
		r = len(matrix[0]) - 1 // 右边界
		t = 0                  // 上边界
		b = len(matrix) - 1    // 下边界
	)
	for {
		// 从左往右
		for i := l; i <= r; i++ {
			fmt.Println(matrix[t][i])
		}
		if t += 1; t > b {
			break
		}
		// 从上到下
		for i := t; i <= b; i++ {
			fmt.Println(matrix[i][r])
		}
		if r -= 1; t < l {
			break
		}
		// 从右往左
		for i := r; i >= l; i-- {
			fmt.Println(matrix[b][i])
		}
		if b -= 1; b < t {
			break
		}
		// 从下往上
		for i := b; i >= t; i-- {
			fmt.Println(matrix[i][l])
		}
		if l += 1; l > r {
			break
		}
	}
}

func main() {
	var (
		matrix = [][]int{
			{1, 2, 3},
			{8, 9, 4},
			{7, 6, 5},
		}
	)
	printMatrix(matrix)
}