Algorithm Race Introductory classic sixth black and white image

Source: Internet
Author: User

Enter a n*n black and white image (1 for black, 0 for White), and the task is to count the number of eight connected blocks. If two black squares have a common edge or a public vertex, they are said to belong to the same eight-connected block.

Sample input:

6
100100
001010
000000
110000
111000
010100

Sample output:

3

Iterate through each black lattice, searching around the center of the black lattice and stopping the search if it is visited (i.e. vis[i][j]=1).

#include <stdio.h> #include <memory.h> #include <string.h> int mat[100][100],vis[100][100];
Char s[100]; void Dfs (int i,int j) {if (vis[i][j]| |
    mat[i][j]==0) return;
    Vis[i][j]=1;
    DFS (I-1,J-1);d FS (I-1,J);d FS (i-1,j+1);              DFS (I,J-1);
    DFS (I,J+1); DFS (I+1,J-1);
DFS (I+1,J);d FS (i+1,j+1);
    } int main (void) {///Freopen ("Black and white image. txt", "R", stdin);
    int i,j,n,count;
        while (scanf ("%d", &n)!=eof) {memset (mat,0,sizeof (MAT));
        memset (vis,0,sizeof (VIS));
        count=0;
            for (i=1;i<=n;i++) {scanf ("%s", s);
            for (j=1;j<=n;j++) {mat[i][j]=s[j-1]-' 0 '; }} for (i=1;i<=n;i++) {for (j=1;j<=n;j++) {if (mat[i
                    ][j]&&vis[i][j]==0) {count++;
                DFS (I,J);
}}} printf ("%d\n", count);    } return 0;
 }


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.