Word Search in Java: Explanation & Practice

Find if word exists in grid

Problem summary

Given a 2D grid of characters and a word, determine if the word exists in the grid. Word can be constructed from adjacent cells (up, down, left, right).

Starter code

public class Main {
    public static void main(String[] args) {
        char[][] board = {
            {'A','B','C','E'},
            {'S','F','C','S'},
            {'A','D','E','E'}
        };
        String word = "ABCCED";
        
        // Backtracking with visited marking
        // Try starting from each cell
        // Print: Found: true
    }
}

Expected output and test cases

  • ABCCED exists
    Found: true
  • SEE exists
    Found: true
  • ABCB doesn't exist
    Found: false

Hints

  1. Try starting DFS from each cell that matches first character
  2. Mark current cell as visited (change to special char)
  3. Try all 4 directions recursively
  4. Restore cell after backtracking

Related Data Structures & Algorithms exercises

Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler