완전 탐색을 하여 2중 for문을 돌린다

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MatchTest : MonoBehaviour
{
    private static readonly int Rows = 4;
    private static readonly int Cols = 4;
    
    private int[,] board =
    {
        {1, 1, 2, 0},
        {1, 1, 1, 1},
        {2, 1, 0, 1},
        {0, 0, 1, 1}
    };
    void Start()
    {
        FindMatchingBlocks();
    }
    
    private void FindMatchingBlocks()
    {
        HashSet<(int, int)> matchedBlocks = new HashSet<(int, int)>();

        for (int i = 0; i < Rows; i++)
        {
            for (int j = 0; j < Cols; j++)
            {
                CheckHorizontalMatch(i, j, matchedBlocks);
                CheckVerticalMatch(i, j, matchedBlocks);
            }
        }

        Debug.Log("Matching Blocks:");
        foreach (var block in matchedBlocks)
        {
            Debug.Log($"({block.Item1}, {block.Item2})");
        }
    }

    private void CheckHorizontalMatch(int row, int col, HashSet<(int, int)> matchedBlocks)
    {
        if (col + 2 < Cols &&
            board[row, col] == board[row, col + 1] &&
            board[row, col] == board[row, col + 2])
        {
            matchedBlocks.Add((row, col));
            matchedBlocks.Add((row, col + 1));
            matchedBlocks.Add((row, col + 2));
        }
    }

    private void CheckVerticalMatch(int row, int col, HashSet<(int, int)> matchedBlocks)
    {
        if (row + 2 < Rows &&
            board[row, col] == board[row + 1, col] &&
            board[row, col] == board[row + 2, col])
        {
            matchedBlocks.Add((row, col));
            matchedBlocks.Add((row + 1, col));
            matchedBlocks.Add((row + 2, col));
        }
    }
}

+ Recent posts