岛屿周长的问题

283 阅读2分钟

岛屿周长问题

给定一个包含 0 和 1 的二维网格地图,其中 1 表示陆地 0 表示水域。

网格中的格子水平和垂直方向相连(对角线方向不相连)。整个网格被水完全包围,但其中恰好有一个岛屿(或者说,一个或多个表示陆地的格子相连组成的岛屿)。

岛屿中没有“湖”(“湖” 指水域在岛屿内部且不和岛屿周围的水相连)。格子是边长为 1 的正方形。网格为长方形,且宽度和高度均不超过 100 。计算这个岛屿的周长。

思考

  1. 计算岛屿的周长,转换为数学问题,就是计算1与0的分界,每一对0与1的都代表着周长加一。

    1. 找出矩阵中的所有1。
    2. 找出每个1周围的0的个数,同时要考虑到该1可能位于边界的情况。

代码

class Solution {
    private static final int[] dx = {-1,0,1,0};
    private static final int[] dy = {0,1,0,-1};
    public int islandPerimeter(int[][] grid) {
        int res = 0;
        for(int i=0;i<grid.length;i++){
            for(int j=0;j<grid[0].length;j++){
                if(grid[i][j] == 1){
                    int sum = 0;
                    for(int k=0;k<4;k++){
                        int x = j + dx[k];
                        int y = i + dy[k];
                        if(x<0||y<0||x==grid[0].length||y==grid.length||grid[y][x] == 0){
                            sum += 1;
                        }
                    }
                    res += sum;
                }
            }
        }
        return res;
    }
}

重新格式化部门表

Create table If Not Exists Department (id int, revenue int, month varchar(5))
Truncate table Department
insert into Department (id, revenue, month) values ('1', '8000', 'Jan')
insert into Department (id, revenue, month) values ('2', '9000', 'Jan')
insert into Department (id, revenue, month) values ('3', '10000', 'Feb')
insert into Department (id, revenue, month) values ('1', '7000', 'Feb')
insert into Department (id, revenue, month) values ('1', '6000', 'Mar')

题目:编写一个 SQL 查询来重新格式化表,使得新的表中有一个部门 id 列和一些对应 每个月 的收入(revenue)列。

答案

SELECT 
    id,
    sum(case when month='Jan' then Revenue else null end) as 'Jan_Revenue',
    sum(case when month='Feb' then Revenue else null end) as 'Feb_Revenue',
    sum(case when month='Mar' then Revenue else null end) as 'Mar_Revenue',
    sum(case when month='Apr' then Revenue else null end) as 'Apr_Revenue',
    sum(case when month='May' then Revenue else null end) as 'May_Revenue',
    sum(case when month='Jun' then Revenue else null end) as 'Jun_Revenue',
    sum(case when month='Jul' then Revenue else null end) as 'Jul_Revenue',
    sum(case when month='Aug' then Revenue else null end) as 'Aug_Revenue',
    sum(case when month='Sep' then Revenue else null end) as 'Sep_Revenue',
    sum(case when month='Oct' then Revenue else null end) as 'Oct_Revenue',
    sum(case when month='Nov' then Revenue else null end) as 'Nov_Revenue',
    sum(case when month='Dec' then Revenue else null end) as 'Dec_Revenue'
FROM Department
GROUP BY id

知识点

本题考查的是将行转化为列。

CASE 列 WHEN 值 THEN 返回值 ELSE 返回值 END语法:如果某列中存在某值然后返回某值如果不存在返回。

IF(EXP,VALUE,VALUE):当EXP为True返回第一个值,反正返回第二个值。