zoukankan      html  css  js  c++  java
  • 洛谷P1141 01迷宫

    洛谷1141 01迷宫

    题目描述

    有一个仅由数字0与1组成的n×n格迷宫。若你位于一格0上,那么你可以移动到相邻4格中的某一格1上,同样若你位于一格1上,那么你可以移动到相邻4格中的某一格0上。
    你的任务是:对于给定的迷宫,询问从某一格开始能移动到多少个格子(包含自身)。

    输入输出格式

    输入格式:

    输入的第1行为两个正整数n,m。
    下面n行,每行n个字符,字符只可能是0或者1,字符之间没有空格。
    接下来m行,每行2个用空格分隔的正整数i,j,对应了迷宫中第i行第j列的一个格子,询问从这一格开始能移动到多少格。

    输出格式:

    输出包括m行,对于每个询问输出相应答案。

    输入输出样例

    输入样例#1:

    2 2

    01

    10

    1 1

    2 2

    输出样例#1:

    4

    4

    说明

    所有格子互相可达。
    对于20%的数据,n≤10; 
    对于40%的数据,n≤50;
    对于50%的数据,m≤5;
    对于60%的数据,n≤100,m≤100;
    对于100%的数据,n≤1000,m≤100000。

    【思路】

      BFS。

      只要相邻节点颜色不同而且未访问则拓展。随读入随操作,如果节点未标记则以该节点拓展。c表示节点颜色,cnt表示颜色的数目。

      注意数组大小一定要开够了,cnt的大小为maxn * maxn。

    【代码】

     1 #include<iostream>
     2 #include<queue>
     3 using namespace std;
     4 
     5 const int maxn = 1000+10;
     6 const int dx[]={0,1,0,-1};
     7 const int dy[]={1,0,-1,0};
     8 struct Node{
     9     int x,y;
    10 };
    11 int G[maxn][maxn];
    12 int c[maxn][maxn];
    13 int cnt[maxn*maxn];
    14 
    15 int n,m;
    16 int colors=1; 
    17 
    18 inline bool inside(int x,int y) {
    19     return x>=0 && x<n && y>=0 && y<n;
    20 }
    21 void bfs(int s,int t) {
    22     queue<Node> q;
    23     q.push((Node){s,t});
    24     c[s][t]=colors; cnt[colors]++;
    25     while(!q.empty()) 
    26     {
    27         Node u=q.front(); q.pop();
    28         int x=u.x , y=u.y;
    29         for(int i=0;i<4;i++)
    30         {
    31             int xx=x+dx[i],yy=y+dy[i];
    32             if(inside(xx,yy) && (G[x][y]!=G[xx][yy]) && c[xx][yy]==0) 
    33             {
    34                    c[xx][yy]=colors; cnt[colors]++;
    35                    q.push((Node){xx,yy});
    36             }
    37         }
    38     }
    39 }
    40 
    41 int main() {
    42     ios::sync_with_stdio(false);
    43     cin>>n>>m;
    44     char ch;
    45     for(int i=0;i<n;i++)
    46       for(int j=0;j<n;j++) {
    47              cin>>ch;
    48              G[i][j]=ch-'0';
    49       }
    50     int x,y;
    51     for(int i=1;i<=m;i++) {
    52         cin>>x>>y;
    53         x--; y--;
    54         colors=i;
    55         if(c[x][y]==0) bfs(x,y);
    56         cout<<cnt[c[x][y]]<<"
    ";
    57     }
    58     return 0;
    59 }
  • 相关阅读:
    韩式英语
    Daily dictation 听课笔记
    words with same pronunciation
    you will need to restart eclipse for the changes to take effect. would you like to restart now?
    glottal stop(britain fountain mountain)
    education 的发音
    第一次用Matlab 的lamada语句
    SVN的switch命令
    String的split
    SVN模型仓库中的资源从一个地方移动到另一个地方的办法(很久才解决)
  • 原文地址:https://www.cnblogs.com/lidaxin/p/4863769.html
Copyright © 2011-2022 走看看