迷宫
#include<bits/stdc++.h>
using namespace std ;
const int N = 10;
int a[N][N];
int ans =0 ;
int n,m,k;
pair<int,int>s , t;
int vis[N][N];
int walk[4][2] ={{0,1},{0,-1},{1,0},{-1,0}};
void dfs(int x,int y){
if(x == t.first && y == t.second){
ans ++;
return ;
}
int dx,dy;
for(int i =0 ; i<4;i++){
dx = x + walk[i][0];
dy = y + walk[i][1];
if(dx >=1 && dx <= n &&dy>=1 &&dy<=m && !a[dx][dy] && !vis[dx][dy]){
vis[dx][dy] =1;
dfs(dx,dy);
vis[dx][dy] =0;
}
}
}
int main(){
ios::sync_with_stdio(false);cin.tie(0);
cin >> n >> m >> k;
cin >> s.first >> s.second >> t.first>>t.second;
for(int i=1;i<=k;i++){
int x,y;cin >> x>> y;
a[x][y] = 1;
}
vis[s.first][s.second] = 1;
dfs(s.first,s.second);
cout<<ans;
return 0;
}
马的遍历
#include<bits/stdc++.h>
using namespace std ;
const int N = 410;
int ans =0 ;
int n,m, sx,sy;
int vis[N][N];
int walk[8][2] ={{2,1},{2,-1},{1,2},{-1,2},{-2,1},{-2,-1},{1,-2},{-1,-2}};
void bfs(){
memset(vis,-1,sizeof vis);
queue<pair<int,int>>q;
q.push({sx,sy});
vis[sx][sy] = 0;
while(!q.empty()){
auto [x,y] = q.front();q.pop();
for(int k = 0 ;k < 8 ;k++){
int dx = x + walk[k][0];
int dy = y + walk[k][1];
if(dx >=1 && dx <= n &&dy>=1 &&dy<=m && vis[dx][dy] == -1){
q.push({dx,dy});
vis[dx][dy] = vis[x][y] + 1;
}
}
}
}
int main(){
ios::sync_with_stdio(false);cin.tie(0);
cin >> n >> m >> sx >> sy;
bfs();
for(int i=1;i<=n;i++){
for(int j = 1; j<= m ;j++){
cout<<vis[i][j]<<" ";
}cout<<"\n";
}
return 0;
}
DFS 全排列
#include<bits/stdc++.h>
using namespace std ;
const int N = 10;
int n,m,k;
int vis[N];
vector<int>tmp;
vector<vector<int>>ans;
void dfs(){
// for(auto i:tmp){
// cout<<i<<" ";
// }cout<<endl;
if(tmp.size() == n){
ans.push_back(tmp);
return ;
}
for(int i=1;i<=n;i++){
if(!vis[i]){
tmp.push_back(i);
vis[i] = 1;
dfs();
tmp.pop_back();
vis[i] = 0;
}
}
}
int main(){
ios::sync_with_stdio(false);cin.tie(0);
cin >> n ;
dfs();
for(auto i:ans){
for(auto v:i){
cout<<v <<" ";
}cout<<"\n";
}
return 0;
}
—— 本文来自火龙信奥(义乌睿码科技):义乌青少年信息学奥赛与编程教育平台,专注 CSP-J/S、NOIP、GESP 竞赛培训,线上线下融合教学,助力编程升学。网址:hlcoding.com