原题链接:红与黑
如果是报错下标越界的话,那么就很有可能是输入的时候的问题,因为这个输入他最后不会是按照一个完整的行来输入的,而是随机的几位数,有可能不到
来个图帮助理解一下
解题思路:
BFS
先将初始坐标加入队列。
然后,遍历当前格子的上下左右四个格子,如果能找到'.',则将他的坐标加入队列。
然后依次做下去,每走到一个新的格子,计数+1
直到队列为空,也就完成了所有遍历。
计数的值就是题解。
这里要注意的事: 在Java中,LinkedList类实现了Queue接口,因此我们可以把LinkedList当成Queue来用。
其中,add()和remove()方法在失败的时候会抛出异常,而offer()和poll()不会,所以这里使用offer()和poll()。
参考代码:
package BFS;
import java.util.*;
class pair {
int x, y;
public pair(int sx, int sy) {
this.x = sx;
this.y = sy;
}
}
public class T3036红与黑BFS {
public static int N = 30;
public static int h, w;
public static char[][] g = new char[N][N];
public static int[] dx = {-1, 0, 1, 0};
public static int[] dy = {0, 1, 0, -1};
static int bfs(int sx, int sy) {
pair p = new pair(sx, sy);
Queue<pair> q = new LinkedList<>();
q.offer(p);
g[sx][sy] = '#';
int res = 0;
while (!q.isEmpty()) {
pair t = q.poll();
res++;
for (int i = 0; i < 4; i++) {
int x = t.x + dx[i];
int y = t.y + dy[i];
if (x < 0 || x >= h || y < 0 || y >= w || g[x][y] != '.') {
continue;
}
g[x][y] = '#';
q.offer(new pair(x, y));
}
}
return res;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (true) {
String[] ts = sc.nextLine().split(" ");
w = Integer.parseInt(ts[0]);
h = Integer.parseInt(ts[1]);
if (w == 0 || h == 0) {
break;
}
int x = 0, y = 0;
for (int i = 0; i < h; i++) {
String str = sc.nextLine();
char[] ch = str.toCharArray();
for (int j = 0; j < ch.length; j++) {
g[i][j] = str.charAt(j);
if (g[i][j] == '@') {
x = i;
y = j;
}
}
}
System.out.println(bfs(x, y));
}
}
}解题思路:
DFS
遍历当前坐标的上下左右四个格子,如果是'.',则立即遍历找到的'.'的格子的上下左右,如此进行递归。
每层递归返回找到的'.'的数量。
最后得到的数量就是题解。
注意:深度优先搜索,由于有很多层递归,有可能爆栈。
虽然DFS代码更加简单,但还是建议使用BFS解决此题。
参考代码:
package DFS;
import java.util.*;
public class T3036红与黑DFS {
public static int N = 30;
public static int h, w;
public static char[][] g = new char[N][N];
public static int[] dx = {-1, 0, 1, 0};
public static int[] dy = {0, 1, 0, -1};
static int dfs(int sx, int sy) {
int res = 1;
g[sx][sy] = '#';
for (int i = 0; i < 4; i++) {
int x = sx + dx[i];
int y = sy + dy[i];
if (x >= 0 && x < h && y >= 0 && y < w && g[x][y] == '.') {
res += dfs(x, y);
}
}
return res;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (true) {
String[] ts = sc.nextLine().split(" ");
w = Integer.parseInt(ts[0]);
h = Integer.parseInt(ts[1]);
if (w == 0 || h == 0) {
break;
}
int x = 0, y = 0;
for (int i = 0; i < h; i++) {
String str = sc.nextLine();
char[] ch = str.toCharArray();
for (int j = 0; j < ch.length; j++) {
g[i][j] = str.charAt(j);
if (g[i][j] == '@') {
x = i;
y = j;
}
}
}
System.out.println(dfs(x, y));
}
}
}0.0分
5 人评分
C语言网提供由在职研发工程师或ACM蓝桥杯竞赛优秀选手录制的视频教程,并配有习题和答疑,点击了解:
一点编程也不会写的:零基础C语言学练课程
解决困扰你多年的C语言疑难杂症特性的C语言进阶课程
从零到写出一个爬虫的Python编程课程
只会语法写不出代码?手把手带你写100个编程真题的编程百练课程
信息学奥赛或C++选手的 必学C++课程
蓝桥杯ACM、信息学奥赛的必学课程:算法竞赛课入门课程
手把手讲解近五年真题的蓝桥杯辅导课程
发表评论 取消回复