A Za, A Za, Fighting...

坚信:勤能补拙

2011搜索-题,DFS,类似计算连通区域的个数

代码:
#include<stdio.h>
#include
<stdlib.h>
#include
<string.h>
#define MAX_NUM 100
#define VALID(x, y) ((x)>=0 && (x)<m && (y)>=0 && (y)<n)
int m, n, count;
char grid[MAX_NUM][MAX_NUM+1];
char visited[MAX_NUM][MAX_NUM+1];

const int dx[] = {-1-1-100111};
const int dy[] = {-101-11-101};
void
dfs_inner(
int x, int y)
{
    
int i, next_x, next_y;
    visited[x][y] 
= 1;
    
for(i=0; i<8++i) {
        next_x 
= x + dx[i];
        next_y 
= y + dy[i];
        
if(VALID(next_x, next_y) && !visited[next_x][next_y] &&
                grid[next_x][next_y]
=='@')
            dfs_inner(next_x, next_y);
    }
}

void
dfs()
{
    
int i, j;
    
for(i=0; i<m; ++i)
        
for(j=0; j<n; ++j)
            
if(!visited[i][j] && grid[i][j]=='@') {
                
++count;
                dfs_inner(i, j);
            }
}

int
main(
int argc, char **argv)
{
    
int i;
    
while(scanf("%d %d"&m, &n)!= EOF && m) {
        count 
= 0;
        memset(visited, 
0sizeof(visited));
        
for(i=0; i<m; ++i)
            scanf(
"%s", grid[i]);
        dfs();
        printf(
"%d\n", count);
    }
}

Oil Deposits
Time Limit: 1000MSMemory Limit: 10000K
Total Submissions: 7595Accepted: 4267

Description

The GeoSurvComp geologic survey company is responsible for detecting underground oil deposits. GeoSurvComp works with one large rectangular region of land at a time, and creates a grid that divides the land into numerous square plots. It then analyzes each plot separately, using sensing equipment to determine whether or not the plot contains oil. A plot containing oil is called a pocket. If two pockets are adjacent, then they are part of the same oil deposit. Oil deposits can be quite large and may contain numerous pockets. Your job is to determine how many different oil deposits are contained in a grid.

Input

The input contains one or more grids. Each grid begins with a line containing m and n, the number of rows and columns in the grid, separated by a single space. If m = 0 it signals the end of the input; otherwise 1 <= m <= 100 and 1 <= n <= 100. Following this are m lines of n characters each (not counting the end-of-line characters). Each character corresponds to one plot, and is either `*', representing the absence of oil, or `@', representing an oil pocket. 

Output

are adjacent horizontally, vertically, or diagonally. An oil deposit will not contain more than 100 pockets.

Sample Input

1 1 * 3 5 *@*@* **@** *@*@* 1 8 @@****@* 5 5  ****@ *@@*@ *@**@ @@@*@ @@**@ 0 0

Sample Output

0 1 2 2 

Source


posted on 2011-08-14 10:29 simplyzhao 阅读(310) 评论(0)  编辑 收藏 引用 所属分类: R_找工复习2011


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   博问   Chat2DB   管理


导航

<2025年1月>
2930311234
567891011
12131415161718
19202122232425
2627282930311
2345678

统计

常用链接

留言簿(1)

随笔分类

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜