Number of cells (breadth-first search)

Source: Internet
Author: User

Title Description:

A rectangular array (n*m) column consists of a number of 0 to 9, the number 1 to 9 represents the cell, the cell is defined as the number of cells along the cell numbers up or down or the cell number is the same cell, the number of cells given a rectangular array. (Cell numbers 1 to 9)

0234500067

1034560500

2045600671

0000000089

There are four of cells

Input:

First line input n and M (n,m<20)

The second line starts with the matrix

Output:

A total number of cells.

Sample input:

4 10

0234500067

1034560500

2045600671

0000000089

Sample output:

4

The subject can be done using breadth-first search;

Use arrays to store input numbers, double loop to find the first cell number and use this as a starting point to search,

The number of cells to be searched is 0,ans++;

Here's a look at the code:

#include <stdio.h>intcell[ -][ -],ans,m,n;//the direction of the two-dimensional array is a bit x, y coordinate size OKintx1[5]={0,1,0,-1,0},y1[5]={0,0,1,0,-1};//using a simple array to represent the direction, the first 0 is meaningless;//two arrays are combined to represent four directions in turnvoidBFsintXinty) {    inti;  for(i=1; i<=4; i++)//find four directions in turnif(x+x1[i]>0&&x+x1[i]<=n&&y+y1[i]>0&&y+y1[i]<=m/*possible to exclude from cross-border*/&&cell[x+x1[i]][y+y1[i]]!=0/*confirm if it's a cell number .*/) {cell[x+x1[i]][y+y1[i]]=0;//will find cell number 0 to prevent duplicationBFS (X+x1[i],y+y1[i]);//search for the next point}}intMain () {scanf ("%d%d",&n,&m); inti,j,k;  for(i=1; i<=n;i++)     for(j=1; j<=m;j++) scanf ("%1d", &cell[i][j]);//no spaces between numbers, "%d" changed to "%1d" for(i=1; i<=n;i++)     for(j=1; j<=m;j++){    if(cell[i][j]!=0) {Cell[i][j]=0;//Don't miss it.BFS (I,J); Ans++; }} printf ("%d", ans);}

Number of cells (breadth-first search)

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.