就三题,不能再多了,贪多嚼不烂
题目1:红与黑
#include <bits/stdc++.h>
using namespace std;
int W,H;
char mp[30][30];
bool vis[30][30];
int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};
int step=0;
bool check(int x,int y) {
if(x>0&&x<=W&&y>0&&y<=H&&vis[x][y]==false&&mp[x][y]=='.'){
return true;
}
else return false ;
}
void dfs(int x,int y){
if(vis[x][y]) return ;
vis[x][y]=true;
step++;
for(int i=0;i<4;i++){
int nx=x+dx[i];
int ny=y+dy[i];
if(check(nx,ny)){
dfs(nx,ny);
}
}
}
int main(){
cin>>W>>H;
for(int i=1;i<=W;i++){
for(int j=1;j<=H;j++){
cin>>mp[i][j];
}
}
for(int i=1;i<=W;i++){
for(int j=1;j<=H;j++){
if(mp[i][j]=='@'){
dfs(i,j);
}
}
}
cout<<step;
return 0;
}
题目二:迷宫的第一条出路
#include <bits/stdc++.h>
using namespace std;
const int N=50;
int n;
char mp[N][N];
bool vis[N][N];
int dx[4] = {0, -1, 0, 1};
int dy[4] = {-1, 0, 1, 0};
struct way{
int start;
int end;
}b[100];
bool check(int x,int y){
if(x>0&&y>0&&x<=n&&y<=n&&!vis[x][y]&&mp[x][y]=='0'){
return true;
}
else return false ;
}
void dfs(int x,int y,int step){
step++;
b[step].start=x;
b[step].end=y;
if (x == n && y == n) {
cout<<"("<<1<<","<<1<<")";
for(int i=3;i<=step;i++){
cout<<"->"<<"("<<b[i].start<<","<<b[i].end<<")";
}
}
if(vis[x][y]) return ;
vis[x][y]=true;
for(int i=0;i<4;i++){
int nx=x+dx[i];
int ny=y+dy[i];
if(check(nx,ny)){
dfs(nx,ny,step);
}
}
}
int main(){
cin>>n;
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
cin>>mp[i][j];
}
}
dfs(1,1,1);
return 0;
}
题目三:迷宫的路径?
#include <bits/stdc++.h>
using namespace std;
const int N=50;
int n,m,flag;
char mp[N][N];
bool vis[N][N];
int dx[4] = {0, 1, 0, -1};
int dy[4] = {1, 0, -1, 0};
struct way{
int start;
int end;
}b[100];
int ans = 0;
bool check(int x,int y){
if(x>0&&y>0&&x<=n&&y<=m&&!vis[x][y]&&mp[x][y]=='o'){
return true;
}
else return false ;
}
void dfs(int x,int y,int step){
step++;
b[step].start=x;
b[step].end=y;
if (x == n && y == m) {
flag=1;
ans++;
cout<<ans<<':';
cout<<1<<","<<1;
for(int i=3;i<=step;i++){
cout<<"->"<<b[i].start<<","<<b[i].end;
}
cout<<endl;
}
vis[x][y]=true;
for(int i=0;i<4;i++){
int nx=x+dx[i];
int ny=y+dy[i];
if(check(nx,ny)){
dfs(nx,ny,step);
}
}
vis[x][y]=0;
}
int main(){
cin>>n>>m;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
cin>>mp[i][j];
}
}
dfs(1,1,1);
if(!flag)
cout<<"no"<<endl;
return 0;
}