- 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.youkuaiyun.com/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 ;
}