I'm stuck
题目并不难,其中一个解决思路,就是把从起点能够遍历到的位置标记上,然后再把从终点把能够遍历的位置标记上,之后筛选出满足题目要求的个数即可。
import java.util.*;
public class Main{
//代表输入的字符
static char[][] g;
//偏移量
static int[] dx = {-1, 0, 1, 0};
static int[] dy = {0, 1, 0, -1};
//从起点能到达的点的标识
static boolean[][] vis1;
//能够到达终点的点的标识
static boolean[][] vis2;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int R = input.nextInt();
int C = input.nextInt();
g = new char[R][C];
vis1 = new boolean[R][C];
vis2 = new boolean[R][C];
for (int i = 0; i < R; i++) {
String str = input.next();
for (int j = 0; j < C; j++) {
g[i][j] = str.charAt(j);
}
}
int x = -1;
int y = -1;
for (int i = 0; i < R; i ++) {
for (int j = 0; j < C; j ++) {
if (g[i][j] == 'S') {
dfs1(i, j);
} else if (g[i][j] == 'T') {
dfs2(i, j);
x = i;
y = j;
}
}
}
if (!vis1[x][y]) {
System.out.println("I'm stuck!");
System.exit(0);
}
int res = 0;
for (int i = 0; i < R; i ++) {
for (int j = 0; j < C; j ++) {
if (vis1[i][j] && !vis2[i][j]) {
res++;
}
}
}
System.out.println(res);
input.close();
}
//标记起点能够到达的节点
private static void dfs1(int x, int y) {
vis1[x][y] = true;
for (int i = 0; i < 4; i++) {
int r = x + dx[i];
int c = y + dy[i];
if (r < 0 || c < 0 || r >= g.length || c >= g[0].length || g[r][c] == '#' || vis1[r][c]) {
continue;
}
//检测从(x,y)能否到达(r,c)
if (check(x, y, i)) {
dfs1(r, c);
}
}
}
//标记重点能够到达的节点
private static void dfs2(int x, int y) {
vis2[x][y] = true;
for (int i = 0; i < 4; i++) {
int r = x + dx[i];
int c = y + dy[i];
if (r < 0 || c < 0 || r >= g.length || c >= g[0].length || g[r][c] == '#' || vis2[r][c]){
continue;
}
//检测能否通过(r,c)到达(x,y)
if (check(r, c, i ^ 2)) {
dfs2(r, c);
}
}
}
private static boolean check(int x, int y, int w) {
char c = g[x][y];
if (c == 'S' || c == '+' || c == 'T') {
return true;
} else if (c == '|' && (w == 0 || w == 2)) {
return true;
} else if (c == '-' && (w == 1 || w == 3)) {
return true;
} else if (c == '.' && w == 2) {
return true;
} else {
return false;
}
}
}
399

被折叠的 条评论
为什么被折叠?



