首先深搜
先看输入格式
5
0 1 0 0 0
0 0 0 1 0
0 1 1 0 0
0 0 1 0 1
1 0 0 0 0
第一行输入一个数n,接下来输入n*n的数字矩阵,0代表房间,1代表墙,每个位置都可以往上下左右四个方向走
题意非常简单,就是求以左上角为出发点所能到达的最多的房间数。
#include<bits/stdc++.h>
using namespace std;
typedef struct{
int x;
int y;
}Point;
const int size = 100+10;
int room[size][size];
int dir[4][2] = {
{-1,0},{1,0},{0,-1},{0,1}
};
int res=0,n;
void dfs(int x,int y){
room[x][y]=1;
res++;
int next_x,next_y;
for(int k=0;k<4;k++){
next_x = x + dir[k][0];
next_y = y + dir[k][1];
if(room[next_x][next_y]==0){
dfs(next_x,next_y);
}
}
}
void dfs_stack(int x,int y){
stack<Point> s;
Point from;
from.x=x;from.y=y;
s.push(from);
while(!s.empty()){
int temp_x=s.top().x;
int temp_y=s.top().y;
room[temp_x][temp_y]=1;
res++;
s.pop();
for(int k=0;k<4;k++){
int next_x = temp_x + dir[k][0];
int next_y = temp_y + dir[k][1];
if(room[next_x][next_y]==0){
Point temp;
temp.x=next_x;
temp.y=next_y;
s.push(temp);
}
}
}
}
int main(){
cin>>n;
for(int i=0;i<=n+1;i++)
for(int j=0;j<=n+1;j++){
if(i==0||i==n+1||j==0||j==n+1)
room[i][j]=1;
else
cin>>room[i][j];
}
dfs_stack(1,1);
cout<<res<<endl;
return 0;
}
再看广搜,
5
0 1 0 0 0
0 0 0 1 0
0 1 1 0 0
0 0 1 0 1
1 0 0 0 0
输入格式和第一个完全一样,1同样代表不可以走,但问题不一样,这个是求从左上角到右下角所需要走的最小的步数。
#include<bits/stdc++.h>
using namespace std;
typedef struct{
int x;
int y;
int steps;
}Point;
const int size = 100+10;
int room[size][size];
int dir[4][2] = {
{-1,0},{1,0},{0,-1},{0,1}
};
int res=0,n;
int bfs_queue(int x,int y,int m,int n){
queue<Point> q;
Point from;
from.x=x;from.y=y;
from.steps=0;
q.push(from);
int steps,flag=0;
while(!q.empty()){
int temp_x=q.front().x;
int temp_y=q.front().y;
steps=q.front().steps;
if(temp_x==m&&temp_y==n){
flag=1;
break;
}
room[temp_x][temp_y]=1;
q.pop();
for(int k=0;k<4;k++){
int next_x = temp_x + dir[k][0];
int next_y = temp_y + dir[k][1];
if(room[next_x][next_y]==0){
Point temp;
temp.x=next_x;
temp.y=next_y;
temp.steps=steps+1;
q.push(temp);
}
}
}
if(flag)return steps;
else return -1;
}
int main(){
cin>>n;
for(int i=0;i<=n+1;i++)
for(int j=0;j<=n+1;j++){
if(i==0||i==n+1||j==0||j==n+1)
room[i][j]=1;
else
cin>>room[i][j];
}
cout<<bfs_queue(1,1,n,n)<<endl;
return 0;
}