Treasure Island Exploration Problem (dfs or recursive solution)

If the sea area is composed of a main island and some subsidiary islands, the sea area can be represented by an n×n square matrix. The numbers in the matrix represent the elevation of the corresponding main island or island: the numbers 1-9 represent land, and the number 0 represents the ocean. 
Now the program Yuaner intends to explore on an island or main island, and his plane will land on the land with sea coordinates (x, y). Please calculate the area of ​​the island or main island where the Yuaner’s landing point is

input
4 4 2 3
1 2 1 0
0 1 1 0
0 1 0 0
0 0 1 0

output
6

Method 1: Obviously this is a search algorithm, that is, as long as the traversal starts from the current coordinate point and counts every time a point is traversed
 

#include<iostream>
using namespace std;
int a[110][110];
int next[4][2]={
   
   {0,1},{0,-1},{1,0},{-1,0}};   //方向数组 
int visit[110][110];//标记数组  标记是否走过 
int sum;  //记录面积大小 
int m,n; //m行 n列 
void dfs(int x,int y)
{
	int tx,ty;
	for(int i=0;i<4;i++)
	{
		tx=x+next[i][0];
		ty=y+next[i][1];
		if(tx<1||tx>n||ty<1||ty>m)  //超出边界则回退 
		continue;
		if(a[tx][ty]>0&&visit[tx][ty]==0) //当前未走过 
		{
			sum++;
			
			visit[tx][ty]=1;
			dfs(tx,ty) ;    
			//visit[tx][ty]=0; //不需要回溯 ?? 
		}
		
	}
}



int  main(void)
{
	int i,j,startx,starty;
	cin>>m>>n>>startx>>starty;
	for(i=1;i<=n;i++)
		for(j=1;j<=m;j++)
			cin>>a[i][j];
	visit[startx][starty]=1;
	sum=1;
	dfs(startx,starty);
	cout<<sum;
	
	return 0;		
}

Method 2: Use recursion

First, how to use recursion to complete DFS? The idea is this, first find the target point, and then diverge from the target point.

How to diverge? Then there must be a direction. Yes, then we need to realize the direction, how to realize it? The array increases or decreases by 1. In the following example, we use an array to indicate the direction.

Then what should we do when we reach the new direction? Continue DFS, yes. How to achieve it? That is recursion.

Wait, do I need DFS every time I get to a new place? Of course not. If the value is what you are looking for, then you will continue to spread, if it is not what you are looking for, then it will not spread. How to achieve it? Add an if statement.

Wait a minute, did you not consider the array out of bounds? That's right, then we still need some judgment statements to ensure that our array does not cross the boundary.

 


int dfs1(int x,int y)  //法2  直接用递归 
{
		if(x<1||x>n||y<1||y>m)
		return 0;
		if(visit[x][y]!=0||a[x][y]==0)
		return 0;
		
		visit[x][y]=1;
		return 1+dfs1(x+1,y)+dfs1(x-1,y)+dfs1(x,y+1)+dfs1(x,y-1); //表示四个方向
		
	
 } 



 

Guess you like

Origin blog.csdn.net/a447332241/article/details/87738621