华为OD机考算法题:开心消消乐

题目部分

题目 开心消消乐
难度
题目说明 给定一个 N 行 M 列的二维矩阵,矩阵中每个位置的数字取值为 0 或 1,矩阵示例如:
1 1 0 0
0 0 0 1
0 0 1 1
1 1 1 1
现需要将矩阵中所有的 1 进行反转为 0,规则如下:
1) 当点击一个 1 时,该 1 被反转为 0,同时相邻的上、下、左、右,以及左上、左下、右上、右下 8 个方向的 1 (如果存在 1)均会自动反转为 0;
2) 进一步地,一个位置上的 1 被反转为 0 时,与其相邻的 8 个方向的 1 (如果存在 1)均会自动反转为 0; 按照上述规则示例中的矩阵只最少需要点击 2 次后,所有均值 0 。请问,给定一个矩阵,最少需要点击几次后,所有数字均为 0?
输入描述 第一行输入两个整数,分别表示矩阵的行数 N 和列数 M,取值范围均为 [1,100] 接下来 N 行表示矩阵的初始值,每行均为 M 个数,取值范围 [0,1]。
输出描述 输出一个整数,表示最少需要点击的次数。
补充说明
------------------------------------------------------
示例
示例1
输入 3 3
1 0 1
0 1 0
1 0 1
输出 1
说明 上述样例中,四个角上的 1 均在中间的 1 的相邻 8 个方向上,因此只需要点击一次即可。
示例2
输入

4 4
1 1 0 0
1 0 0 0
0 0 0 1
0 0 1 1 

输出 2
说明 在上述 4 * 4 的矩阵中,只需要点击 2 次(左上角 和 右下角),即可将所有的 1 消除。


解读与分析

题目解读

点击一个 1,它相邻八个方向的 1 变成 0,与此同时,这八个方向如果存在 1 变成 0,那么与它相邻的八个方向的 1 也会变成 0。

有点像扫雷游戏。

分析与思路

此题可以采用广度优先搜索或深度优先搜索,遍历所有点击的情况。然后根据所有点击情况,计算出最小的点击次数。

时间复杂度为 O(n^{2}),空间复杂度为 O(n^{2})。

与《华为OD机考算法题:机器人活动区域》有些类似。


代码实现

Java代码

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;

/**
 * 开心消消乐
 * 
 * @since 2023.10.13
 * @version 0.2
 * @author Frank
 *
 */
public class HappyCollapse {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		while (sc.hasNext()) {
			String line = sc.nextLine();
			String[] rc = line.split(" ");
			int row = Integer.parseInt(rc[0]);
			int column = Integer.parseInt(rc[1]);

			int[][] matrix = new int[row][column];
			for (int i = 0; i < row; i++) {
				line = sc.nextLine();
				String[] strColumnValue = line.split(" ");
				int[] number = new int[column];
				for (int j = 0; j < column; j++) {
					number[j] = Integer.parseInt(strColumnValue[j]);
				}
				matrix[i] = number;
			}

			processHappyCollapse(matrix, row, column);
		}

	}

	static class Node {
		int i;
		int j;

		public Node(int i, int j) {
			this.i = i;
			this.j = j;
		}

		@Override
		public int hashCode() {
			return (i + " " + j).hashCode();
		}

		@Override
		public boolean equals(Object obj) {
			if (!(obj instanceof Node))
				return false;
			Node node = (Node) obj;
			return node.i == i && node.j == j;
		}
	}

	private static void processHappyCollapse(int[][] matrix, int row, int column) {
		Set<Node> nodeSet = new HashSet<Node>();
		List<Node> nodeList = new ArrayList<Node>();
		for (int i = 0; i < row; i++) {
			for (int j = 0; j < column; j++) {
				if (matrix[i][j] == 1) {
					Node node = new Node(i, j);
					nodeList.add(node);

					nodeSet.add(node);
				}
			}
		}

		int[] rowColumn = new int[2];
		rowColumn[0] = row;
		rowColumn[1] = column;

		int minCnt = Integer.MAX_VALUE;
		for (int i = 0; i < nodeList.size(); i++) {
			List<Node> copyOfList = new ArrayList<Node>();
			copyOfList.addAll(nodeList);

			Set<Node> copyOfSet = new HashSet<Node>();
			copyOfSet.addAll(nodeSet);

			Node node = nodeList.get(i);

			copyOfList.remove(i);
			copyOfSet.remove(node);

			int cnt = startClickNode(node, copyOfList, copyOfSet, rowColumn);
			if (cnt < minCnt) {
				minCnt = cnt;
			}
		}
		System.out.println(minCnt);

	}

	private static int startClickNode(Node node, List<Node> nodeList, Set<Node> nodeSet, int[] rowColumn) {
		int clickCnt = 1;
		clickCollapseNode(node, nodeList, nodeSet, rowColumn);

		if (nodeList.size() == 0) {
			return 1;
		}

		int minCnt = Integer.MAX_VALUE;
		for (int i = 0; i < nodeList.size(); i++) {
			List<Node> copyOfList = new ArrayList<Node>();
			copyOfList.addAll(nodeList);

			Set<Node> copyOfSet = new HashSet<Node>();
			copyOfSet.addAll(nodeSet);

			Node curNode = nodeList.get(i);

			copyOfList.remove(i);
			copyOfSet.remove(curNode);

			int cnt = startClickNode(curNode, copyOfList, nodeSet, rowColumn);
			if (cnt < minCnt) {
				minCnt = cnt;
			}

		}
		return clickCnt + minCnt;
	}

	private static void clickCollapseNode(Node node, List<Node> nodeList, Set<Node> nodeSet, int[] rowColumn) {
		int row = rowColumn[0];
		int column = rowColumn[1];

		if (node.i >= 1) {
			colapseNode(new Node(node.i - 1, node.j), nodeList, nodeSet, rowColumn);
		}
		if (node.i < row - 1) {
			colapseNode(new Node(node.i + 1, node.j), nodeList, nodeSet, rowColumn);
		}
		if (node.j >= 1) {
			colapseNode(new Node(node.i, node.j - 1), nodeList, nodeSet, rowColumn);
		}
		if (node.j < column - 1) {
			colapseNode(new Node(node.i, node.j + 1), nodeList, nodeSet, rowColumn);
		}
		if (node.i >= 1 && node.j >= 1) {
			colapseNode(new Node(node.i - 1, node.j - 1), nodeList, nodeSet, rowColumn);
		}
		if (node.i >= 1 && node.j < column - 1) {
			colapseNode(new Node(node.i - 1, node.j + 1), nodeList, nodeSet, rowColumn);
		}
		if (node.i < row - 1 && node.j >= 1) {
			colapseNode(new Node(node.i + 1, node.j - 1), nodeList, nodeSet, rowColumn);
		}
		if (node.i < row - 1 && node.j < column - 1) {
			colapseNode(new Node(node.i - 1, node.j + 1), nodeList, nodeSet, rowColumn);
		}
	}

	private static void colapseNode(Node node, List<Node> nodeList, Set<Node> nodeSet, int[] rowColumn) {
		if (nodeSet.contains(node)) {
			nodeList.remove(node);
			nodeSet.remove(node);
			clickCollapseNode(node, nodeList, nodeSet, rowColumn);
		}
	}

}

JavaScript代码

const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;
void async function() {
    while (line = await readline()) {
        var rowColumn = line.split(" ");
        var row = parseInt(rowColumn[0]);
        var column = parseInt(rowColumn[1]);

        var matrix = new Array();
        for (var i = 0; i < row; i++) {
            line = await readline();
            var strNumbers = line.split(" ");
            var numbers = new Array(column);
            for (var j = 0; j < column; j++) {
                numbers[j] = parseInt(strNumbers[j]);
            }
            matrix[i] = numbers;
        }

        processHappyCollapse(matrix, row, column);
    }
}();

function processHappyCollapse(matrix, row, column) {
    var nodeSet = new Set();
    var nodeList = new Array();
    for (var i = 0; i < row; i++) {
        for (var j = 0; j < column; j++) {
            if (matrix[i][j] == 1) {
                var node = i + "," + j;
                nodeList.push(node);
                nodeSet.add(node);
            }
        }
    }

    var rowColumn = new Array();
    rowColumn[0] = row;
    rowColumn[1] = column;

    var minCnt = Number.MAX_VALUE;
    for (var i = 0; i < nodeList.length; i++) {
        var copyOfList = Array.from(nodeList);
        var copyOfSet = new Set(nodeSet);

        var node = nodeList[i];

        copyOfList.splice(i, 1);
        copyOfSet.delete(node);

        var cnt = startClickNode(node, copyOfList, copyOfSet, rowColumn);
        if (cnt < minCnt) {
            minCnt = cnt;
        }
    }
    console.log(minCnt);
}

function startClickNode(node, nodeList, nodeSet, rowColumn) {
    var clickCnt = 1;
    clickCollapseNode(node, nodeList, nodeSet, rowColumn);

    if (nodeList.length == 0) {
        return 1;
    }

    var minCnt = Number.MAX_VALUE;
    for (var i = 0; i < nodeList.length; i++) {
        var copyOfList = Array.from(nodeList);
        var copyOfSet = new Set(nodeSet);

        var curNode = nodeList[i];

        copyOfList.splice(i, 1);
        copyOfSet.delete(curNode);

        var cnt = startClickNode(curNode, copyOfList, nodeSet, rowColumn);
        if (cnt < minCnt) {
            minCnt = cnt;
        }
    }
    return clickCnt + minCnt;
}

function clickCollapseNode(node, nodeList, nodeSet, rowColumn) {
    var row = rowColumn[0];
    var column = rowColumn[1];

    var nodeStrValue = node.split(",");
    var nodeValue = new Array();
    nodeValue[0] = parseInt(nodeStrValue[0]);
    nodeValue[1] = parseInt(nodeStrValue[1]);

    for (var i = -1; i <= 1; i++) {
        if (nodeValue[0] + i < 0 || nodeValue[0] + i > row - 1) {
            continue;
        }
        for (var j = -1; j <= 1; j++) {
            if (i == 0 && j == 0) {
                continue;
            }
            if (nodeValue[1] + j < 0 || nodeValue[1] + j > column - 1) {
                continue;
            }
            colapseNode((nodeValue[0] + i) + "," + (nodeValue[1] + j), nodeList, nodeSet, rowColumn);
        }
    }

}

function colapseNode(node, nodeList, nodeSet, rowColumn) {
    if (nodeSet.has(node)) {
        var idx = nodeList.indexOf(node);
        nodeList.splice(idx, 1);
        nodeSet.delete(node);
        clickCollapseNode(node, nodeList, nodeSet, rowColumn);
    }
}

虽然此题的难度标记为“易”,实际编码量比较大。难度并不小,在短时间内写出代码并不是很容易。

(完)

猜你喜欢

转载自blog.csdn.net/ZiJinShi/article/details/133760638