插: 前些天发现了一个巨牛的人工智能学习网站,普通易懂,风趣幽默,不由得分享一下给各人。点击跳转到网站。
坚持不懈,越积极越荣幸,各人一起学习鸭~~~
标题:
给你一个 m x n 的矩阵 mat 和一个整数 k ,请你返回一个矩阵 answer ,此中每个 answer[j] 是全部满足下述条件的元素 mat[r][c] 的和:
i - k <= r <= i + k,
j - k <= c <= j + k 且
(r, c) 在矩阵内。
示例 1:
输入:mat = [[1,2,3],[4,5,6],[7,8,9]], k = 1
输出:[[12,21,16],[27,45,33],[24,39,28]]
示例 2:
输入:mat = [[1,2,3],[4,5,6],[7,8,9]], k = 2
输出:[[45,45,45],[45,45,45],[45,45,45]]
提示:
m == mat.length
n == mat.length
1 <= m, n, k <= 100
1 <= mat[j] <= 100
java代码:
class Solution { public int[][] matrixBlockSum(int[][] mat, int k) { int m = mat.length,n = mat[0].length; int[][] dp = get_dp(mat,m,n); return get_res(dp,m,n,k);}//获取dp数组public int[][] get_dp(int[][] arr,int m,int n){ int[][] dp = new int[m+1][n+1]; for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) dp[i+1][j+1] = dp[j+1]+dp[i+1][j]+arr[j]-dp[j]; return dp;}//获取效果public int[][] get_res(int[][] dp,int m,int n,int k){ int[][] res = new int[m][n]; int x1,y1,x2,y2; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { x1 = Math.max(0,i-k);y1 = Math.max(0,j-k); x2 = Math.min(m,i+k+1);y2 = Math.min(n,j+k+1); res[j] = dp[x2][y2]-dp[x1][y2]-dp[x2][y1]+dp[x1][y1]; } } return res;}} |