885. 螺旋矩阵 III

题目链接:https://leetcode-cn.com/problems/spiral-matrix-iii/
算法思路:https://www.cnblogs.com/grandyang/p/10887598.html
https://leetcode-cn.com/problems/spiral-matrix-iii/solution/luo-xuan-ju-zhen-iii-by-leetcode/

class Solution(object):
    def spiralMatrixIII(self, R, C, r0, c0):
        """
        :type R: int
        :type C: int
        :type r0: int
        :type c0: int
        :rtype: List[List[int]]
        """
        res = [[r0, c0]]
        X = [0, 1, 0, -1]#(r,c)
        Y = [1, 0, -1, 0]
        cur, step = 0, 0
        while len(res) < R * C:
            if cur == 0 or cur == 2:
                step += 1
            for _ in range(0, step, 1):
                r0 += X[cur]
                c0 += Y[cur]
                if r0 < R and r0 >= 0 and c0 < C and c0 >= 0:
                    res.append([r0, c0])
            #print(cur)
            cur = (cur + 1) % 4
        print(res)
        return res

x = Solution()
R = 1
C = 4
r0 = 0
c0 = 0
x.spiralMatrixIII(R, C, r0, c0)
package main

import "fmt"

func spiralMatrixIII(R int, C int, r0 int, c0 int) [][]int {
	var res [][]int
	//东南西北,
	X := []int{0, 1, 0, -1} //r0相当于南北
	Y := []int{1, 0, -1, 0} //c0东西
	cur, step := 0, 0
	res = append(res, []int{r0, c0})
	for len(res) < R * C {
		if cur == 0 || cur == 2 {
			step ++
		}
		for i := 0; i < step; i ++ {
			r0 += X[cur]
			c0 += Y[cur]
			if r0 < R && r0 >= 0 && c0 < C && c0 >= 0 {
				res = append(res, []int{r0, c0})
				fmt.Println(res, len(res))
			}
		}
		cur = (cur + 1) % 4
	}
	fmt.Println(res)
	return res
}

func main() {
	R, C, r0, c0 := 1, 4, 0, 0
	spiralMatrixIII(R, C, r0, c0)
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值