463. 岛屿的周长【简单题】
思路:【DFS】
代码:
class Solution {
public int islandPerimeter(int[][] grid) {
int ans = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == 1){
ans += dfs(grid,i,j);
}
}
}
return ans;
}
public int dfs(int[][] grid,int i,int j){
int[] dx = {-1,0,1,0},dy = {0,-1,0,1};
int cnt1 = 0;
for (int k = 0; k < 4; k++) {
int x = i+dx[k],y = j+dy[k];
if (x>=0 && x< grid.length && y>=0 && y<grid[0].length){
if (grid[x][y] == 1){
cnt1++;
}
}
}
return 4-cnt1;
}
}
用时:
比官方题解的dfs快一点点
661. 图片平滑器【简单题】
思路:【DFS】
代码:
class Solution {
public int[][] imageSmoother(int[][] img) {
int rows = img.length,cols = img[0].length;
int[][] ans = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
ans[i][j] = dfs(img,i,j);
}
}
return ans;
}
public int dfs(int[][] img,int i,int j){
int[][] directions = {{-1,-1},{0,-1},{1,-1},{-1,0},{1,0},{-1,1},{0,1},{1,1}};
int sum = img[i][j],count = 1;
for (int k = 0; k < 8; k++) {
int x = i + directions[k][0],y = j + directions[k][1];
if (x>=0 && x<img.length && y>=0 && y<img[0].length){
sum += img[x][y];
count++;
}
}
return (int) Math.floor(sum/count);
}
}
用时:
11ms,菜了。
注:
今天的每日一题还是不会写,以后有机会再研究一下,会写的时候再发上来。