(Supplement) 20200911: Solve the problem of the 204 Weekly Competition

Likou 204 Weekly Competition Problem Solved

topic

3.1568. Minimum number of days to separate land
Insert picture description here

Ideas and algorithms

  1. The third question of this week’s contest can barely be seen, and the fourth question is beyond my current level, so skip it. The third question is a typical dfs or bfs question, the same type of question connecting islands or dividing islands. It is basically over when you notice that the answer can only be 0, 1, or 2. Pay attention to writing. See code

Code


class Solution {
    
    
	int m, n;
	boolean[][] used;
	// 表示上下左右
	private static final int[][] directions = {
    
     {
    
     0, 1 }, {
    
     0, -1 }, {
    
     -1, 0 }, {
    
     1, 0 } };

	public int minDays(int[][] grid) {
    
    
		m = grid.length;
		n = grid[0].length;
		used = new boolean[m][n];
		if (numOfLand(grid)) {
    
    
			return 0;
		} else {
    
    
			// 枚举 去掉其中一个1看能不能满足
			for (int i = 0; i < m; i++) {
    
    
				for (int j = 0; j < n; j++) {
    
    
					if (grid[i][j] == 1) {
    
    
						grid[i][j] = 0;
						if (numOfLand(grid)) {
    
    
							return 1;
						}
						grid[i][j] = 1;
					}
				}
			}
			return 2;
		}
	}

	public boolean numOfLand(int[][] grid) {
    
    
		// 计算是否有多个连通块,或者0个连通块
		int count = 0;
		used = new boolean[m][n];
		for (int i = 0; i < m; i++) {
    
    
			for (int j = 0; j < n; j++) {
    
    
				if (!used[i][j] && grid[i][j] == 1) {
    
    
					count++;
					dfs(grid, i, j);
				}
			}
		}
		return count > 1 || count == 0;
	}

	public void dfs(int[][] grid, int i, int j) {
    
    
		used[i][j] = true;
		for (int k = 0; k < 4; k++) {
    
    
			int x = i + directions[k][0];
			int y = j + directions[k][1];
			if (inside(x, y) && !used[x][y] && grid[i][j] == 1) {
    
    
				dfs(grid, x, y);
			}
		}
	}

	public boolean inside(int x, int y) {
    
    
		return x >= 0 && x < m && y >= 0 && y < n;
	}
}

Write at the end

Rush!

Guess you like

Origin blog.csdn.net/qq_36828395/article/details/108558116