扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
作者:赛迪网 李丝 来源:天新网 2008年3月22日
关键字: 数据库 Mssql SQL Server SQL
在本页阅读全文(共6页)
算法问题:用SQL写出当M*N时的螺旋矩阵算法
以下是一个4*4的矩阵:
1 12 11 10
2 13 16 9
3 14 15 8
4 5 6 7
请照上面矩阵的规律, 用SQL写出当M*N时的矩阵算法。
实现的sql与效果:
代码:---------------------------------------------
SQL> -- 逆时针的
SQL> select --i,
2 sum(decode(j, 1, rn)) as co11,
3 sum(decode(j, 2, rn)) as co12,
4 sum(decode(j, 3, rn)) as co13,
5 sum(decode(j, 4, rn)) as co14
6 from (select i, j, rank() over(order by tag) as rn
7 from (select i,
8 j,
9 -- 逆时针螺旋特征码 counter-clockwise
10 case least(j - 1, 4 - i, 4 - j, i - 1)
11 when j - 1 then
12 (j - 1) || "1" || i
13 when 4-i then
14 (4 - i) || "2" || j
15 when 4 - j then
16 (4 - j) || "3" || (4 - i)
17 when i - 1 then
18 (i - 1) || "4" || (4 - j)
19 end as tag
20 from (select level as i from dual connect by level <= 4) a,
21 (select level as j from dual connect by level <= 4) b))
22 group by i
23 /
CO11 CO12 CO13 CO14
---------- ---------- ---------- ----------
如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。