通法:dfs里全是if 没有return,dfs的参数一般只需要坐标和棋盘,偶尔会有boolean[][] 看需要
ps: if{1进入状态值,2进入dfs}
lc 79 单词搜索
res是返回值,bool类型设置为公共变量,24行不能走的地方就直接return。12行最后一个参数要加0,棋盘回溯本不用加0,这题有word相当于有长度限制,要加0,记录长度。
lc200 岛屿问题
迷宫问题
import java.util.Scanner;
public class Solution {
static char[][] qipan;
static int[][] status;
static int m,n;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
m = sc.nextInt();
n = sc.nextInt();
qipan = new char[m][n];
status = new int[m][n];
sc.nextLine();
int ox = 0,oy = 0;
for (int i = 0; i < m; i++) {
String str = sc.nextLine();
char[] chars = str.toCharArray();
for (int j = 0; j < chars.length; j++) {
qipan[i][j] = chars[j];
if(chars[j]== '0'){
ox = i;
oy = j;
}
}
}
recursion(ox,oy);
int count = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if(status[i][j] == 0) count++;
}
}
count--;
System.out.println(count);
}
private static void recursion(int x, int y) {
if(x - 1 >=0&& status[x-1][y] ==0 && (qipan[x - 1][y] == 'D' || qipan[x - 1][y] == '.')){
status[x-1][y] = 1;
recursion(x-1,y);
}
if(x + 1 <= (n -1) && status[x+1][y] ==0 && (qipan[x + 1][y] == 'U' || qipan[x + 1][y] == '.')){
status[x+1][y] = 1;
recursion(x+1,y);
}
if(y - 1 >=0&& status[x][y-1] ==0 && (qipan[x][y - 1] == 'R' || qipan[x][y - 1] == '.')){
status[x][y - 1] = 1;
recursion(x,y - 1);
}
if(y + 1 <= (n -1) && status[x][y + 1] ==0 && (qipan[x][y + 1] == 'L' || qipan[x][y + 1] == '.')){
status[x][y + 1] = 1;
recursion(x,y + 1);
}
}
}