dfs--cell problem

Source: Internet
Author: User

Topic: 1009: Cell
Description
A rectangular array is made up of numbers 0 through 9, and numbers 1 to 9 represent cells.
The cell is defined as the same cell, along the cell number or the cell number.
The number of cells in the given rectangular array is obtained.
such as array
4 10
0234500067
1034560500
2045600671
0000000089
There are 4 cells.
Input
The first row contains 2 integers, n, and M, representing the number of rows and columns of the rectangular array, respectively.
The next n rows, each row m number, represent the cell's rectangular array.
Output
The number of output cells.
Sample Input
4 10
0234500067
1034560500
2045600671
0000000089
Sample Output
4 This problem can be solved with DFS and BFS, where DFS DFS code is used first:


Main.cpp//dfs--cell Issue///Created by Showlo on 2018/4/16. COPYRIGHT©2018 year Showlo.
All rights reserved.
#include <stdio.h> #include <algorithm> using namespace std;
#define MAX 1000 char Map[max][max];
int Vis[max][max];

int m,n;
    void Dfs (int x,int y) {int i,nx,ny;
    int dx[4]={1,0,-1,0};
    int dy[4]={0,1,0,-1};
        for (i=0; i<4; i++) {nx=x+dx[i];
       Ny=y+dy[i];
        printf ("%d%d\n", nx,ny); if (nx>=0&&nx<m&&ny>=0&&ny<n&&map[nx][ny]!= ' 0 ' &&vis[nx][ny]
            ==0) {//If added condition: &map[nx][ny]==map[x][y], you can calculate the number of cells under the same condition//printf ("%d%d\n", nx,ny);
            Vis[nx][ny]=1;
        DFS (NX,NY);
    else continue;
} return;
    int main () {int i,j,num;
        while (scanf ("%d%d", &m,&n)!=eof) {num=0;
        memset (Vis, 0, sizeof (VIS));
        For (i=0 i<m; i++) {scanf ("%s", Map[i]);
 }       For (i=0 i<m; i++) {for (j=0; j<n; J + +) {if (vis[i][j]==0&&map[i][j]!=
                    ' 0 ') {printf ("%d%d\n\n", i,j);
                    num++;
                    Vis[i][j]=1;
                DFS (I,J);
            else continue;
    } printf ("%d\n", num);
return 0; }

BFS Code:


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.