当前位置:网站首页>蓝桥杯31天冲刺 Day10
蓝桥杯31天冲刺 Day10
2022-04-22 05:38:00 【柴可拉夫斯基】
扫地机器人
链接: 扫地机器人

全球变暖
链接: 全球变暖.

贴一道力扣题,和这个相似:链接: 200. 岛屿数量.
AC代码:
class Solution {
public int numIslands(char[][] grid) {
int count=0;
for(int i =0;i<grid.length;i++){
for(int j=0;j<grid[i].length;j++){
if(grid[i][j] == '1'){
count++;
islands(grid,i,j);
}
}
}
return count;
}
public void islands(char[][] grid,int i,int j){
grid[i][j] = '0';
int[] dx = {
1,0,-1,0};
int[] dy = {
0,1,0,-1};
for(int k =0;k<4;k++){
int xx = i+dx[k];
int yy = j+dy[k];
if(xx>=0&&yy>=0&&xx<grid.length&&yy<grid[0].length){
if(grid[xx][yy] == '1')
islands(grid,xx,yy);
}
}
}
}
相当于BFS+DFS
主要就是遇到空地‘#’就进行判断、更改
我们将k记作临近水域的空地
w记为不临近水域的空地
通过BFS判断是否有空地可以更改
通过DFS进行周围空地的更改
完整代码:
package 题库;
import java.util.*;
public class 全球变暖 {
public static int[] dx = {
-1,0,1,0};
public static int[] dy = {
0,-1,0,1};
public static int n;
public static char[][] picture;
public static int island(int i,int j) {
int res = 0;
//判断#周围是否有水域(修改k)
for(int k =0;k<4;k++) {
int xx = i+dx[k];
int yy = j+dy[k];
if(xx<0||xx>=n||yy<0||yy>=n||picture[xx][yy]!='.')
continue;
picture[i][j] = 'k';
}
//修改w
if(picture[i][j] !='k') {
picture[i][j] = 'w';
res++;
}
//递归修改该岛屿其他部分
for(int k =0;k<4;k++) {
int xx = i+dx[k];
int yy = j+dy[k];
if (xx < 0 || yy < 0 || xx >= n || yy >= n) {
continue;
}
if(picture[xx][yy] == '#')
res+=island(xx,yy);
}
return res;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int pre=0;
int after=0;
n = sc.nextInt();
picture = new char[n][n];
for(int i =0;i<n;i++) {
picture[i] = sc.next().toCharArray();
}
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
if(picture[i][j] == '#') {
pre++;
if(island(i,j)>0)
after++;
}
}
}
System.out.println(pre-after);
}
}
版权声明
本文为[柴可拉夫斯基]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_53421929/article/details/123554863
边栏推荐
猜你喜欢

Common methods of arrays (super detailed explanation)

LeetCode 2044. 统计按位或能得到最大值的子集数目 --深度遍历

Digital DP (template)

Data mining -- naive Bayesian classification

LeetCode 514. 自由之路--动态规划

vs 断点无法调试 The breakpoint will not currently be hit. No symbols have been loaded for this document.

SQL面试题总结(更新中)

IDEA值得推荐的20款优秀的插件

stl alloc 空间分配器 代码解析

The breakpoint will not currently be hit No symbols have been loaded for this document.
随机推荐
How to use on duplicate key update in MySQL
JVM exploration
torch 循环神经网络torch.nn.RNN()和 torch.nn.RNNCell()
MySQL command
LeetCode 514. 自由之路--动态规划
AcWing 836. 合并集合(并查集)
根源:pip终端下载的包import不能用
imdecode 源码解读
关于form表单点击submit按钮后,页面自动刷新的问题解决
Code analysis of STL alloc space allocator
通过设置关联菜单建立excel记账本
conda命令
数据挖掘——数据预处理
Machine learning -- drawing P-R curve and ROC curve with iris data set
Complete knapsack problem
Common methods of arrays (super detailed explanation)
LeetCode 99. 恢复二叉搜索树 -- 中序遍历+排序
Simple DP questions - cow breeding and super stair climbing
卷积神经网络
The ECDSA host key for raspberrypi.local has changed 解决方案