Java P1331 海战

题目链接
首先判断一下船只是否碰撞,然后再dfs

import java.util.*;
import java.math.*;
public class Main {
     
	public static int[] dx={
     1,1,-1,-1,0,0,1,-1};
	public static int[] dy={
     -1,1,1,-1,1,-1,0,0};
	public static char[][] map;
	public static int res=0;
    public static void main(String[] args){
     
    	Scanner sc=new Scanner(System.in);
    	int n=sc.nextInt();
    	int m=sc.nextInt();
    	map=new char[n][m];
    	sc.nextLine();
    	for(int i=0;i<n;i++){
     
    		String s=sc.nextLine();
    		map[i]=s.toCharArray();
    	}
    	if(is()){
     
    		for(int i=0;i<n;i++){
     
    			for(int j=0;j<m;j++){
     
    				if(map[i][j]=='#'){
     
    					dfs(i,j);
    					res++;
    				}
    			}
    		}
    		System.out.println("There are "+res+ " ships.");
    		
    	}else
    		System.out.println("Bad placement."); 
    }
    public static boolean is(){
     
    	int r=map.length;
    	int c=map[0].length;
    	for(int i=0;i<r-1;i++){
     
    		for(int j=0;j<c-1;j++){
     
    			int a=0;
    			if(map[i][j]=='#')
    				a++;
    			if(map[i+1][j]=='#')
    				a++;
    			if(map[i][j+1]=='#')
    				a++;
    			if(map[i+1][j+1]=='#')
    				a++;
    			if(a==3)
    				return false;
    			
    		}
    	}
    	return true;
    }
    public static void dfs(int x,int y){
     
    	int r=map.length;
    	int c=map[0].length;
    	if(x<0||y<0||x==r||y==c||map[x][y]=='.')
    		return;
    	map[x][y]='.';
    	for(int i=4;i<8;i++){
     
    		dfs(x+dx[i],y+dy[i]);
    	}
    }
}

你可能感兴趣的:(洛谷,java,dfs,java)