Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,900 questions

51,831 answers

573 users

How to check if a grid is a valid word square (same words horizontally and vertically) in Java

1 Answer

0 votes
import java.util.List;
import java.util.ArrayList;

public class Solution {
    public static boolean validWordSquares(List<String> grid) {
        for (int i = 0; i < grid.size(); i++) {
            for (int j = 0; j < grid.get(i).length(); j++) {
                if (i >= grid.size() || j >= grid.size() || j >= grid.get(i).length() || i >= grid.get(j).length()) {
                    return false;
                }
                if (grid.get(i).charAt(j) != grid.get(j).charAt(i)) {
                    return false;
                }
            }
        }
        return true;
    }

    public static void main(String[] args) {
        List<String> grid = new ArrayList<>();
        
        grid.add("abcde");
        grid.add("bvqz");
        grid.add("cqm");
        grid.add("dz");
        grid.add("e");
        
        System.out.println(validWordSquares(grid));
    }
}

  
   
/*
run
   
true
   
*/

 



answered Jun 3, 2024 by avibootz
...