计蒜客 引爆炸弹

题目链接

考点:

dfs,注意规定方向,炸弹一定是一炸到底的。

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
import java.util.Vector;

public class Main {
	static int n, m, cnt = 0;
	static boolean vis[][] = new boolean[1005][1005];
	static char mp[][] = new char[1005][1005];
	public static void dfs(int x, int y, int dis) {

		if (x < 0 || x >= n || y < 0 || y >= m || vis[x][y])
			return;
		if (mp[x][y] == '1' && vis[x][y] == false) {
			vis[x][y] = true;
			dfs(x, y + 1, 0);
			dfs(x + 1, y, 1);
			dfs(x, y - 1, 2);
			dfs(x - 1, y, 3);
		}
		if(dis == 0)dfs(x, y + 1, 0);
		if(dis == 1)dfs(x + 1, y, 1);
		if(dis == 2)dfs(x, y - 1, 2);
		if(dis == 3)dfs(x - 1, y, 3);
	}

	public static void main(String[] args) {
		Scanner cin = new Scanner(System.in);
		n = cin.nextInt();
		m = cin.nextInt();
		for (int i = 0; i < n; i++) {
			String s = cin.next();
			for (int j = 0; j < m; j++)
			{
				mp[i][j] = s.charAt(j);
			}
		}
		for (int i = 0; i < n; i++)
			for (int j = 0; j < m; j++) {
				if (mp[i][j] == '1' && vis[i][j] == false) {
					dfs(i, j, 0);
					cnt++;
				}
			}
		System.out.println(cnt);
	}
}

你可能感兴趣的:(蓝桥杯,dfs)