Sudoku Válido

Aprende a validar un Sudoku 9x9 de LeetCode 36 verificando filas, columnas y cajas 3x3 con HashSet. Guía clara y eficiente con análisis de complejidad y enfoque práctico.

16 ago 2025 • 3 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

LeetCode #36 Valid Sudoku Reescrito y traducido

Resumen de la solución La solución comprueba que un tablero de Sudoku 9 por 9 sea válido verificando filas, columnas y las nueve cajas 3 por 3. Para cada fila, columna y caja se utiliza un conjunto HashSet que evita duplicados de dígitos del 1 al 9 y se ignoran las celdas vacías representadas por el carácter punto.

Verificación de filas Se recorren las nueve filas con un bucle externo. Para cada fila se crea un nuevo HashSet y se recorren las nueve celdas de esa fila. Si la celda no es punto y el intento de añadir el dígito al conjunto falla, significa que hay un duplicado y el tablero no es válido.

Verificación de columnas De forma análoga a las filas, se recorren las nueve columnas con un bucle externo. Para cada columna se crea un HashSet nuevo y se recorren las celdas en esa columna. Si aparece un dígito repetido el método devuelve false.

Verificación de las cajas 3 por 3 Esta es la parte más delicada porque hay que mapear coordenadas de caja a posiciones del tablero. Las cajas pueden identificarse por dos índices boxRow y boxCol que toman valores 0, 1 y 2 formando las nueve combinaciones Box(0,0) Box(0,1) Box(0,2) Box(1,0) Box(1,1) Box(1,2) Box(2,0) Box(2,1) Box(2,2).

Bucle exterior de selección de caja Se usan dos bucles: for int boxRow = 0; boxRow < 3; boxRow++ y for int boxCol = 0; boxCol < 3; boxCol++. boxRow indica la fila de cajas y boxCol la columna de cajas, generando así las nueve cajas.

Conversión de coordenadas de caja a coordenadas del tablero Para recorrer las posiciones dentro de una caja se usan bucles anidados: for int i = boxRow * 3; i < boxRow * 3 + 3; i++ y for int j = boxCol * 3; j < boxCol * 3 + 3; j++. La fórmula clave es multiplicar boxRow y boxCol por 3 para obtener el índice inicial de la submatriz 3 por 3.

Ejemplo caja superior izquierda Box 0,0 boxRow 0 y boxCol 0 producen i 0,1,2 y j 0,1,2. Se revisan las posiciones [0,0] [0,1] [0,2] [1,0] [1,1] [1,2] [2,0] [2,1] [2,2].

Ejemplo caja central Box 1,1 boxRow 1 y boxCol 1 producen i 3,4,5 y j 3,4,5. Se revisan las posiciones [3,3] [3,4] [3,5] [4,3] [4,4] [4,5] [5,3] [5,4] [5,5].

Ejemplo caja inferior derecha Box 2,2 boxRow 2 y boxCol 2 producen i 6,7,8 y j 6,7,8. Se revisan las posiciones [6,6] [6,7] [6,8] [7,6] [7,7] [7,8] [8,6] [8,7] [8,8].

Validación dentro de cada caja Para cada caja se crea un HashSet nuevo y se añaden los dígitos encontrados. Si un dígito ya existe en el HashSet la validación falla y la función devuelve false. Este mismo patrón se aplica a filas y columnas.

Complejidad y notas prácticas El algoritmo recorre como máximo las 81 celdas del tablero un número constante de veces por fila, columna y caja, por lo que su coste es lineal en el tamaño del tablero y en la práctica constante para un Sudoku estándar. Es sencillo, claro y eficiente para validar tableros iniciales de Sudoku.

Acerca de Q2BSTUDIO Q2BSTUDIO es una empresa de desarrollo de software especializada en aplicaciones a medida y software a medida para empresas de todos los tamaños. Ofrecemos servicios avanzados en inteligencia artificial e ia para empresas, desarrollo de agentes IA, ciberseguridad y consultoría en servicios cloud aws y azure. Además brindamos soluciones de servicios inteligencia de negocio y visualización con power bi para convertir datos en decisiones accionables. Nuestros proyectos combinan experiencia en inteligencia artificial, ciberseguridad y arquitectura cloud para entregar aplicaciones a medida seguras y escalables.

Palabras clave y posicionamiento aplicaciones a medida software a medida inteligencia artificial ciberseguridad servicios cloud aws y azure servicios inteligencia de negocio ia para empresas agentes IA power bi

Contacto y llamada a la acción Si quieres desarrollar una solución personalizada, mejorar la seguridad de tus sistemas, implementar inteligencia artificial en tus procesos o migrar a la nube con servicios cloud aws y azure, contacta con Q2BSTUDIO y transformemos tus ideas en productos de alto valor.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.

Live Chat