1 条题解

  • 0
    @ 2025-5-6 20:10:39

    解题思路

    1. 输入处理
      • 使用 while 循环读取矩阵大小 n,当 n 为 0 时结束循环。
      • 初始化字符矩阵 grid 和辅助矩阵 map
      • 读取 n×n 的字符矩阵 grid,将 grid 中值为 X 的位置在 map 中标记为 1,表示障碍。
    2. 填充函数 paint
      • 函数 paint 用于对给定位置 (x, y) 进行填充操作。
      • 根据 map[x][y] 的值进行处理,如果 map[x][y] 等于 num,则将 map[x][y] 置为 0,否则将 map[x][y] 置为 num,并记录 tobe 的值。
      • (x, y) 的上下左右四个方向进行遍历,当遇到非 X 的位置且 map 值等于 num 时,将其 map 值置为 tobe
    3. 深度优先搜索函数 dfs
      • dfs 函数用于进行深度优先搜索。
      • y 等于 n 时,说明当前行已经处理完,递归调用 dfs 处理下一行。
      • x 等于 n 时,说明整个矩阵已经处理完,更新结果 res 为当前填充数量 fillinres 中的较大值。
      • 如果 map[x][y] 大于 0,说明该位置是障碍或者已经处理过,递归调用 dfs 处理下一个位置。
      • 如果 map[x][y] 等于 0,先调用 paint 函数进行填充操作,然后递归调用 dfs 处理下一个位置,填充后再调用 dfs 不进行填充的情况。
    4. 输出结果
      • main 函数中,调用 dfs(0, 0) 开始搜索,输出最终的结果 res,即最多可以填充的区域数量。
    #include<iostream>
    #include<cstring>
    using namespace std;
    
    char grid[4][4];
    int n,res,map[4][4];
    
    void paint(int x, int y, int num){
    	int tobe;
    	if(map[x][y] == num)
    		map[x][y] = 0, tobe = 0;
    	else
    		map[x][y] = num, tobe = num, num = 0;
    	int k = x+1;
    	while(k<n&&grid[k][y]!='X'){
    		if(map[k][y]==num)
    			map[k][y] = tobe;
    		k++;
    	}
    	k = y+1;
    	while(k<n&&grid[x][k]!='X'){
    		if(map[x][k]==num)
    			map[x][k] = tobe;
    		k++;
    	}
    	k = x-1;
    	while(k>=0&&grid[k][y]!='X'){
    		if(map[k][y]==num)
    			map[k][y] = tobe;
    		k--;
    	}
    	k = y-1;
    	while(k>=0&&grid[x][k]!='X'){
    		if(map[x][k]==num)
    			grid[x][k] = tobe;
    		k--;
    	}
    }
    
    
    void dfs(int x, int y, int flag, int fillin){
    	//cout << x << " " << y << endl;
    	if(y==n){
    		dfs(x+1,0,flag,fillin);
    		return;
    	}
    	if(x==n){
    		res = max(res,fillin);
    		return;
    	}
    	
    	if(map[x][y]>0){
    		dfs(x,y+1,flag,fillin);
    	}
    	else{
    		paint(x,y,flag);
    		dfs(x,y+1,flag+1,fillin+1);
    		paint(x,y,flag);
    		dfs(x,y+1,flag,fillin);
    	}
    }
    
    
    int main(){
    	while(cin>>n&&n){
    		memset(map,0,sizeof(map));
    		for(int i = 0; i < n; i++)
    			for(int j = 0; j < n; j++)
    				cin >> grid[i][j];
    		for(int i = 0; i < n; i++)
    			for(int j = 0; j < n; j++)
    				if(grid[i][j]=='X')
    					map[i][j] = 1;
    		res = 0;
    		dfs(0,0,2,0);
    		cout << res << endl;
    	}
    }
    
    • 1

    信息

    ID
    316
    时间
    1000ms
    内存
    256MiB
    难度
    10
    标签
    递交数
    1
    已通过
    1
    上传者