zoukankan      html  css  js  c++  java
  • 洛谷 P1162 填涂颜色__(刷题)bfs

    这道题做的比较坎坷,还曾经RE了......

    比较基础的BFS ,要反着来考虑。

    考虑:没有被全包围的0,标记。

    题目戳这里

     1 #include<bits/stdc++.h>
     2 using namespace std;
     3 const int maxn=1e6 + 5;
     4 
     5 int xx[4] = {0,0,1,-1};
     6 int yy[4] = {1,-1,0,0};
     7 int maps[35][35];
     8 int used[35][35];
     9 int n;
    10 
    11 struct node
    12 {
    13     int x,y;
    14 };
    15 
    16 
    17 void print()
    18 {
    19     for(int i=0;i<n;i++)
    20         for(int j=0;j<n;j++)
    21            if(used[i][j]) maps[i][j]=3;
    22     for(int i=0;i<n;i++)
    23     {
    24         for(int j=0;j<n;j++)
    25         {
    26             if(maps[i][j]==3) printf("0 ");
    27             else if(maps[i][j]==0) printf("2 ");
    28             else printf("1 ");
    29         }
    30         printf("
    ");
    31     }
    32 }
    33 
    34 void bfs(int a,int b)
    35 {
    36     queue<node> q;
    37     if(maps[a][b]==1) return;
    38     q.push(node{a,b});
    39     used[a][b] = 1;
    40     while(!q.empty())
    41     {
    42         node p=q.front();
    43         q.pop();
    44         for(int i=0;i<4;i++)
    45         {
    46             int dx = p.x+xx[i];
    47             int dy = p.y+yy[i];
    48             if(dx<0 || dx>n-1 || dy<0 || dy>n-1) continue;
    49             if(used[dx][dy]) continue;
    50             if(maps[dx][dy]) continue;
    51             used[dx][dy] = 1;
    52             q.push(node{dx,dy});
    53         }
    54     }
    55 }
    56 int main()
    57 {
    58     scanf("%d",&n);
    59     for(int i=0;i<n;i++)
    60        for(int j=0;j<n;j++) scanf("%d",&maps[i][j]);
    61     for(int i=0;i<n;i++) bfs(i,0);
    62     for(int i=0;i<n;i++) bfs(0,i);
    63     for(int i=0;i<n;i++) bfs(i,n-1);
    64     for(int i=0;i<n;i++) bfs(n-1,i);
    65     print();
    66     return 0;
    67 }
  • 相关阅读:
    Move Zeroes
    Intersection of Two Arrays II
    Intersection of Two Arrays
    Create Maximum Number
    Leetcode version 2
    JDBC学习笔记
    九章算法基础班
    九章算法强化班
    LeetCode
    Amazon High Frequent 9 problems
  • 原文地址:https://www.cnblogs.com/pengcheng-official/p/9457119.html
Copyright © 2011-2022 走看看