import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class Main { public static boolean ok = false; public static int move[][] = { { 1, 0 }, { 0, 1 }, { -1, 0 }, { 0, -1 } }; public static int x, y; public static int x1, y1; public static int cn, m; public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNext()) { ok = false; int a, b; a = sc.nextInt(); b = sc.nextInt(); cn = a; m = b; x1 = -1; y1 = -1; x = 0; y = 0; char[][] xy = new char[a][b]; for (int i = 0; i < a; i++) { xy[i] = sc.next().toCharArray(); } for (int i = 0; i < a; i++) { for (int j = 0; j < b; j++) { if (xy[i][j] == 's') { x = i; y = j; } if (xy[i][j] == 'g') { x1 = i; y1 = j; } } } if (x1 == -1) { System.out.println("No"); } else { find(x, y, xy); if (ok == true) { System.out.println("Yes"); } else { System.out.println("No"); } } } } private static void find(int x, int y, char[][] xy) { if (x == x1 && y == y1) { ok = true; return; } if (ok == true) { return; } for (int i = 0; i < 4; i++) { int xx = x + move[i][0]; int yy = y + move[i][1]; if (xx >= 0 && xx < cn && yy >= 0 && yy < m && xy[xx][yy] != '#' && ok == false) { xy[xx][yy] = '#'; find(xx, yy, xy); xy[xx][yy] = '.'; } } return; } }
想到没出口后也错了
import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class Main { public static boolean ok = false; public static int move[][] = { { 1, 0 }, { 0, 1 }, { -1, 0 }, { 0, -1 } }; public static int x, y; public static int x1, y1; public static int cn, m; public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNext()) { ok = false; int a, b; a = sc.nextInt(); b = sc.nextInt(); cn = a; m = b; x1 = -1; y1 = -1; x = 0; y = 0; char[][] xy = new char[a][b]; for (int i = 0; i < a; i++) { xy[i] = sc.next().toCharArray(); } for (int i = 0; i < a; i++) { for (int j = 0; j < b; j++) { if (xy[i][j] == 's') { x = i; y = j; } if (xy[i][j] == 'g') { x1 = i; y1 = j; } } } if (x1 == -1) { System.out.println("No"); } else { find(x, y, xy); if (ok == true) { System.out.println("Yes"); } else { System.out.println("No"); } } } } private static void find(int x, int y, char[][] xy) { if (x == x1 && y == y1) { ok = true; return; } if (ok == true) { return; } for (int i = 0; i < 4; i++) { int xx = x + move[i][0]; int yy = y + move[i][1]; if (xx >= 0 && xx < cn && yy >= 0 && yy < m && xy[xx][yy] != '#' && ok == false) { xy[xx][yy] = '#'; find(xx, yy, xy); xy[xx][yy] = '.'; } } return; } }
全部评论
(1) 回帖