LeetCode in Swift: Word Search

Problem Statement

Given a 2D board and a word, find if the word exists in the grid.

The word can be constructed from letters of sequentially adjacent cell, where “adjacent” cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

For example,
Given board =

word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.

Original LeetCode problem page

My Solution in Swift

Recursive version:

Iterative version:

The recursive version runs twice as fast as the iterative version (57 ms vs 116 ms). In the iterative implementation, I used a stack array to record traversed node information so that the program can later backtrack if needed. This doesn’t work as efficient as the same kind of automatic information book keeping in recursion.

Try It Yourself

1: each links to a blog post of mine that is dedicated to the problem
2: total execution time of a solution on my MacBook Pro (Late 2013, 2.6 GHz Intel Core i7, 16 GB 1600 MHz DDR3). Each solution is compiled with following command:

$ swiftc -O -sdk `xcrun --show-sdk-path --sdk macosx` json.swift main.swift -o mySolution

The total execution time is the average of 10 runs.
3: these test cases are semi-automatically :P retrieved from LeetCode Online Judge system and are kept in JSON format
4: each Xcode project includes everything (my Swift solution to a problem, its JSON test cases and a driver code to test the solution on those test cases)

Problem1Time2Test Cases3My Xcode Project4
Word Search57.457ms Save  (2001) Save  (1926)

More Problems Solved in Swift

My full list of LeetCode problems attempted using Swift