洛谷普及场(广搜)

  • P1605迷宫

dfs搜索基础题,dfs搜索时每次搜索完要记得将转态还原

#include <cstdio>
const int N = 8 ; 
int n , m , t , ans ;
int maze[N][N] ; 
int dir[4][2] = {{-1,0},{0,-1},{1,0},{0,1}} ; 
int a , b , c , d ;
void dfs(int x1 , int y1 , int x2 , int y2){
	int x , y ;
	if (x1 == x2 && y1 == y2){
		ans ++ ; 
		return ; 
	} 
	for (int i = 0 ; i < 4 ; ++i){
		x = x1 + dir[i][0] ; 
		y = y1 + dir[i][1] ; 
		if (x>=1&&x<=n&&y>=1&&y<=m && !maze[x][y]){
			maze[x][y] = 1 ; 
			dfs(x,y,x2,y2) ; 
			maze[x][y] = 0 ;	//还原没走过的转态否则后面的走不了 
		}   
	}
}
int main(){
	scanf ("%d%d%d",&n,&m,&t) ;
	scanf ("%d%d",&a,&b) ;
	scanf ("%d%d",&c,&d) ;  
	int x , y ;
	for (int i = 1 ; i <= t ; ++i){
		scanf ("%d%d",&x,&y) ; 
		maze[x][y] = 1 ; 
	}
	maze[a][b] = 1 ; 
	dfs(a,b,c,d) ; 
	printf ("%d\n",ans) ; 
	return 0 ;  
}
  • P1141 01迷宫

  • 单独开了一篇博客:https://blog.csdn.net/coder370/article/details/101625931

  • P1443 马的遍历
    普通的搜索题,但是是象棋马的走法,一开始以为就是普通的上下左右(尴尬.jpg)

#include <cstdio>
#include <queue>
using namespace std ; 
const int N = 410 ; 
int dir[8][2] = {{-2,-1},{-1,-2},{1,-2},{2,-1},{2,1},{1,2},{-2,1},{-1,2}} ; 
int chess[N][N] ;
struct node{
	int x , y ; 
}; 
int n , m ; 
bool vis[N][N] ; 
int step ; 
void bfs(int x , int y){
	vis[x][y] = true ; 
	chess[x][y] = 0 ;
	queue<node> q ;
	node head , next ;
	head.x = x , head.y = y ;  
	q.push(head) ; 
	while(!q.empty()){
		head = q.front() ; 
		q.pop() ;
		for (int i = 0 ; i < 8 ; i ++){
			next.x = head.x + dir[i][0] , next.y = head.y + dir[i][1] ;
			if (next.x>=0&&next.x<n && next.y>=0&&next.y<m && !vis[next.x ][next.y]){
				chess[next.x ][next.y] = chess[head.x][head.y] + 1 ; 
				vis[next.x ][next.y] = true ;
				q.push(next) ; 
			}
		}
	}
	
}
int main(){
	int x , y ;   
	scanf ("%d%d%d%d",&n,&m,&x,&y) ;
	bfs(x-1,y-1) ; 
	for (int i = 0 ; i < n ; ++i){
		for (int j = 0 ; j < m ; ++j){
			if (chess[i][j] == 0){
				if (i == x-1 && j == y-1)
					printf ("%-5d",0) ; 
				else	printf ("%-5d",-1) ; 
			}
			else	printf ("%-5d",chess[i][j]) ; 
		}
		printf ("\n") ; 
	}
	return 0 ; 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值