Question about pre-increament in java


  • 0
    W
    public class Solution {
        public boolean exist(char[][] board, String word) {
            for (int i = 0; i < board.length; i++) {
                for (int j = 0; j < board[0].length; j++) {
                    if(dfs(board, word, i, j, 0)) return true;
                }
            }
            return false;
        }
        
        private boolean dfs(char[][] board, String word, int i, int j, int index) {
            if (index == word.length()) {
                return true;
            }
            if (Math.min(i, j) < 0 || i >= board.length || j >= board[0].length) {
                return false;
            }
            if (board[i][j] != word.charAt(index)) {
                return false;
            }
            char c = board[i][j];
            board[i][j] = '#';
            boolean re = dfs(board, word, i + 1, j, index + 1)||
                         dfs(board, word, i - 1, j, index + 1)||
                         dfs(board, word, i, j + 1, index + 1)||
                         dfs(board, word, i, j - 1, index + 1);
            board[i][j] = c;
            return re;
        }
    }
    

    Code above is working. But if I change this part (from "index + 1" to "++index" ), it won't work. Can someone help me to understand why

        boolean re = dfs(board, word, i + 1, j, ++index)||
                     dfs(board, word, i - 1, j, ++index)||
                     dfs(board, word, i, j + 1, ++index)||
                     dfs(board, word, i, j - 1, ++index);

  • 1
    L

    you 4 conditions are OR, so if one failed, the index will be increased, that is why you cannot use ++.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.