1739. 迷宫的所有路径-深度优先搜索-DFS

代码:

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
int n;
int fx[4]={0,1,0,-1};
int fy[4]={1,0,-1,0};
bool vis[100][100];
int q[35][3];
int c;
void print(int k){
	c++;
	cout<<c<<":";
	for(int i=1;i<=k;i++){
		cout<<q[i][1]<<","<<q[i][2];
		if(i!=k){
			cout<<"->";
		}
		
	}
	cout<<endl;
}
void dfs(int x,int y,int k){
	q[k][1]=x;
	q[k][2]=y;
	if(x==n&&y==n){
		print(k);
		
	}
	else{
		int tx,ty;
		for(int i=0;i<4;i++){
			tx=x+fx[i];
			ty=y+fy[i];
			
			if(tx>=1&&tx<=n&&ty>=1&&ty<=n&&vis[tx][ty]==false){
				vis[tx][ty]=true;
				dfs(tx,ty,k+1);	
				vis[tx][ty]=false; 
			}
				
				
		}
		
	}
}
int main(){
	cin>>n;
	vis[1][1]=true;
	
	dfs(1,1,1);
	return 0;
}
相关推荐
非优秀程序员2 小时前
第05章 播放器大战,暴风、快播与那一夜|《互联网产品恩仇录》
算法
武子康8 小时前
驾驶轨迹换个坐标,就能给移动机器人用吗?
人工智能·算法·机器学习
lisw0514 小时前
Dayhoff的PAM替换矩阵理论评介!
线性代数·算法·矩阵
一起学安全技术15 小时前
拆大模型 03|注意力的一句话版本:不用论文讲清 Attention
深度学习·算法·语言模型·transformer
Delightrs16 小时前
Rust LeetCode238 算法题解
开发语言·算法·rust
自信1504130575917 小时前
重生之从0开始学习c++之——vector-中篇
c++·学习·算法
GoAI1 天前
DeepSeek Harness Memory (一)主流记忆插件总结
后端·算法·面试
Pniubi1 天前
力扣54.螺旋矩阵
算法·leetcode·矩阵