dfs深搜暴力总结

在这里插入图片描述

走路径类型

走方格

这道题dfs会超时,仅作参考。

本题求路径总数,且起点固定1,1,终点固定n,m
设置vis数组判断这个格子是否走过,避免重复走。
dfs(1,1)表示从1,1出发,因此需要把这个格子标记为true。


import java.io.*;
import java.util.*;
public class eighth {
	static int N=35;
	static int M=35;
	
	static int count=0;
	static int n,m;
	
	static int a[][]=new int[N][M];
	static int f[][]=new int[N][M];
	static boolean isVisited[][]=new boolean[N][M];
	static int dx[]= {0,1};
	static int dy[]= {1,0};
	
	public static void dfs(int x,int y) {

		if(x==n && y==m) {
			count++;
			return;
		}
		
		for(int i=0;i<2;i++) {
			int xx=x+dx[i];
			int yy=y+dy[i];
			
			if(xx<1 ||yy<1 || xx>n || yy>m) continue;//边界错了
			if(xx%2==0 && yy%2==0) continue;
			if(isVisited[xx][yy]) continue;
			
			isVisited[xx][yy]=true;
			dfs(xx,yy);
			isVisited[xx][yy]=false;
		}
	}
	
	public static void main(String args[]) {
		Scanner sc=new Scanner(System.in);
		n=sc.nextInt();
		m=sc.nextInt();
		
		isVisited[1][1]=true;//这里忘记标记
		dfs(1,1);
		dp();
		System.out.println(count+" "+f[n][m]);
	}
}

摆花P1970

在这里插入图片描述

这道题可使用贪心,这里叙述暴力搜索逻辑(会超时):
枚举所有方案(每株花有选与不选的可能),最后check是否合法,O(2^n)的做法。

选择类型

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值