Huawei OD computer-based test algorithm questions: Happy Xiaoxiaole

Question part

topic Happy Xiaoxiaole
difficulty easy
Question description Given a two-dimensional matrix with N rows and M columns, the number at each position in the matrix has a value of 0 or 1. An example of the matrix is:
1 1 0 0 a>
0 0 0 1
0 0 1 1
1 1 1 1
Now we need to convert the matrix All 1's in are reversed to 0, the rules are as follows:
1) When a 1 is clicked, the 1 is reversed to 0, and at the same time, the adjacent upper, lower, left, and right And 1 in the eight directions of upper left, lower left, upper right and lower right (if 1 exists) will be automatically reversed to 0;
2) Further, a 1 at a position is reversed to When 0, the 1s in the 8 adjacent directions (if there are 1s) will be automatically inverted to 0; according to the above rules, the matrix in the example only needs to be clicked at least 2 times, and all mean values ​​will be 0. Given a matrix, what is the minimum number of clicks required before all numbers are 0?
Enter description The first line inputs two integers, which respectively represent the number of rows N and the number of columns M of the matrix. The value range is [1,100]. The next N lines represent the initial value of the matrix. Each row contains M numbers, and the value range is [ 0,1].
Output description Output an integer representing the minimum number of clicks required.
Additional information none
------------------------------------------------------
Example
Example 1
enter 3 3
1 0 1
0 1 0
1 0 1
output 1
illustrate In the above example, the 1's on the four corners are all 8 directions adjacent to the 1 in the middle, so only one click is needed.
Example 2
enter

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

output 2
illustrate In the above 4 * 4 matrix, you only need to click 2 times (upper left corner and lower right corner) to eliminate all 1's.


Interpretation and analysis

Item explanation

Click a 1, and the 1s in its eight adjacent directions will turn into 0s. At the same time, if there are 1s in these eight directions that turn into 0s, then the 1s in the eight adjacent directions will also turn into 0s.

It's a bit like a Minesweeper game.

Analysis Yoshiro

This question can use breadth-first search or depth-first search to traverse all click situations. Then calculate the minimum number of clicks based on all clicks.

The time complexity of is O(n^{2}) and the space complexity is O(n^{2}).

is somewhat similar to "Huawei OD computer-based test algorithm questions: Robot activity area".


Code

Java code

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 code

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);
    }
}

Although the difficulty of this question is marked as "easy", the actual coding amount is relatively large. The difficulty is not small, and it is not easy to write code in a short time.

(over)

Guess you like

Origin blog.csdn.net/ZiJinShi/article/details/133760638