lanqiao OJ141 穿越雷区

简介: lanqiao OJ141 穿越雷区

1.穿越雷区 - 蓝桥云课 (lanqiao.cn)

这个题没什么难度,bfs搜索路径,多了一个方向的遍历条件,找到A点和B点的位置,记录下来,

然后用bfs搜索,1.mp[x][y] !=mp[tx][ty] ,就是要求当前的位置的字符和马上要走到的位置的字符不能相同。

#include<iostream>
#include<string>
#include<algorithm>
#include<queue>
 
using namespace std ;
const int N = 110 ;
int n ;
int fx,fy ;
char mp[N][N];
bool v[N][N] ;
int d[4][2] = {{0,1},{0,-1},{1,0},{-1,0}} ;
struct node{//用于记录存入队列的点的位置,和走了多少步才到了这里。
  int x , y , dis ;
  node(int xx , int yy  ,int diss){
    x = xx , y = yy  , dis = diss ; 
  } 
};
queue<node> q ;
 
void bfs(){
  while(!q.empty()){
    node now = q.front() ;
    q.pop() ;
    int x = now.x , y = now.y  , dis = now.dis ;
    if(x==fx&&y==fy){
      cout << dis << endl ; return ;
    }
    for(int i = 0 ; i < 4 ; i ++){
      int tx = x + d[i][0] , ty = y + d[i][1] ;
      if(tx<0 || tx >= n || ty < 0 || ty >= n ||(mp[tx][ty] == mp[x][y]) || v[tx][ty]) continue ;//当前点的字符和马上要走的点的字符不同
        v[tx][ty] = 1 ;
        q.push(node(tx,ty,dis+1));
      
    }
  }
}
 
int main(){
  cin >> n ;
 
  for(int i = 0 ; i < n ; i ++){
    for(int j = 0; j < n ; j ++){
      cin >> mp[i][j];
      if(mp[i][j] == 'A') {
        v[i][j] = 1 ;
        q.push({i,j,0}) ;
      }
      if(mp[i][j] == 'B') fx = i , fy = j ;
    }
  }
  
  bfs() ;
  
  return 0 ;
}
目录
相关文章
|
3天前
lanqiao OJ 1505 剪邮票
lanqiao OJ 1505 剪邮票
10 0
|
3天前
lanqiao OJ 689 四阶幻方
lanqiao OJ 689 四阶幻方
10 0
|
3天前
lanqiao OJ 364 跳石头
lanqiao OJ 364 跳石头
18 6
|
3天前
lanqiao OJ 89 路径之谜
lanqiao OJ 89 路径之谜
8 1
|
3天前
lanqiao OJ 229 迷宫与陷阱
lanqiao OJ 229 迷宫与陷阱
10 1
|
1天前
lanqiao oj 机房
lanqiao oj 机房
7 1
|
3天前
lanqiao OJ 525 传球游戏
lanqiao OJ 525 传球游戏
11 2
|
3天前
lanqiao OJ 3513 岛屿个数(2023省赛)
lanqiao OJ 3513 岛屿个数(2023省赛)
9 2
|
3天前
lanqiao OJ 108 发现环
lanqiao OJ 108 发现环
8 1
|
3天前
lanqiao OJ 网络寻路
lanqiao OJ 网络寻路
8 0